How can I discard 10*10 pixels from WebGL alternately - javascript

I have drawn a square using webgl. I want to make the square checkered board. So What I need to do is I need to discard some 10*10 pixels alternately from the square. How can I use
gl_FragCoord.x and gl_FragCoord.x
To achieve this? Or is there any easy idea?

WARNING: untested.
You could do math on the fragment shader to create the checker board pattern. First do integer division of x and y by 10 and you get the tile coordinates, lets call it i and j. Then add i and j together. If the result of that is odd, discard the fragments, else if even, keep the fragments.

Related

Find the largest rectangle that fits inside a polygon

I need to find the largest rectangle that can fit inside any polygon,
what i tried is dividing the svg to 2d grid and loop the 2d array to see if the current grid cell intersects with the polygon to create a new 2d binary array where intersection is 1 else 0
now i need to find the largest rectangle from that 2d array AND more importantly its location
as example:
if the 2d array is like this, i need to find the largest rect in that array and its x1,y1 (start i,j) and x2,y2 (end i,j).
well you can brute force the location and scan for the size which will be O(n^6) if n is the avg size of side of your map in pixels ...
The location might be speed up by search (accepting not strictly sorted data) for example like this:
How approximation search works
which would lead to ~O(n^4.log^2(n)). But beware the search must be configured properly in order to not skip solution ... The size search can be improved too by using similar technique like I did in here:
2D OBB
Just use different metric so I would create LUT tables of start and end positions for each x and y (4 LUT tables) which will speed up the search leading to ~O(n^2.log^2(n)) while creation of LUT is O(n^2). btw the same LUTs I sometimes use in OCR like here (last 2 images):
OCR and character similarity
Now problem with this approach is it can not handle concave polygon correctly as there might be more edges per x,y than just 2. So to remedy that you would need to have more LUTs and use them based on position in polygon (divide polygon to "convex" areas)
So putting all these together would look something like this:
approx loop (center x) // ~O(log(n))
approx loop (center y) // ~O(log(n))
grow loop (square size to max using) LUT // O(n)
{
grow loop (x size to max while decreasing original square y size) // O(n)
grow loop (y size to max while decreasing original square x size) // O(n)
use bigger from the above 2 rectangles
}
Just do not forget to use area of polygon / area of rectangle as approximation error value. This algo is resulting in ~O(n^2.log^2(n)) which is not great but still doable.
Another option is convert your polygon to squares, and use bin-packing and or graph and or backtracking techniques to grow to biggest rectangle ... but those are not my cup of tea so I am not confident enough to create answer about them.

How to use different drawArrays types in one program using WebGL?

I have an assignment with little context on how to actually implement what the professor is asking (I am also a novice at Javascript, but I know a ton about c and c++). The WebGL program must render 3 different types of drawArray calls: POINTS, TRIANGLE_FAN, and LINES.
I have different arrays for each, respectively, and I know how to draw one type at a time, but I am unsure as to how to draw 3 different types.
Should all the vectors be put into one giant array? I tried doing this method and the first TRIANGLE_FAN would draw correctly, but calling drawArrays again with the other two types, and setting the offset to be the 'first' index of a line, and then a 'point', gave me the errors:
WebGL error INVALID_OPERATION in drawArrays(ONE, 36, 2)
WebGL error INVALID_OPERATION in drawArrays(NONE, 40, 1)
Alternatively, using separate arrays for each type, and setting buffers for each, how do you go about drawArrays when there is more than one array set to 'gl' -> (getWebGLContext(canvas))?
For reference, this is what the professor assigned:
Write a WebGL program that displays a rotating pendulum. The
pendulum bob is free to rotate through 360 degrees about an anchor
point at the center of the canvas. The pendulum has the following
three components.
1) The anchor point is a green square centered at the origin
(0,0) with point size = 5 pixels.
2) The bob is a blue hexagon of radius r = 0.1. Render this with
a triangle fan centered at the origin (along with a ModelView
matrix that translates and rotates).
3) The bob is attached to the anchor point by a rigid red wire of
length l = 0.8.
Use global variables for the point size of the anchor, the radius
of the bob, the length of the wire, and the angular velocity of
rotation in degrees per second. Set the initial angular velocity
to 45 and allow an interactive user to increase or decrease the
value in multiples of 10 degrees per second with button presses.
It's up to you. WebGL doesn't care as long as you specify things correctly. In your case if you put them the same buffer you need to specify offsets to each piece data.
The most common way would be to put the data for each draw call in its own buffers.
also the first argument to drawArrays is the primitive type (POINT, LINE, TRIANGLES, etc) not ONE or NONE has you've put in your question
You might want to check out some tutorials on webgl

Determine if a 2D point is within a quadrilateral

I'm working on a JS program which I need to have determine if points are within four corners in a coordinate system.
Could somebody point me in the direction of an answer?
I'm looking at what I think is called a convex quadrilateral. That is, four pretty randomly chosen corner positions with all angles smaller than 180°.
Thanks.
There are two relatively simple approaches. The first approach is to draw a ray from the point to "infinity" (actually, to any point outside the polygon) and count how many sides of the polygon the ray intersects. The point is inside the polygon if and only if the count is odd.
The second approach is to go around the polygon in order and for every pair of vertices vi and vi+1 (wrapping around to the first vertex if necessary), compute the quantity (x - xi) * (yi+1 - yi) - (xi+1 - xi) * (y - yi). If these quantities all have the same sign, the point is inside the polygon. (These quantities are the Z component of the cross product of the vectors (vi+1 - vi) and (p - vi). The condition that they all have the same sign is the same as the condition that p is on the same side (left or right) of every edge.)
Both approaches need to deal with the case that the point is exactly on an edge or on a vertex. You first need to decide whether you want to count such points as being inside the polygon or not. Then you need to adjust the tests accordingly. Be aware that slight numerical rounding errors can give a false answer either way. It's just something you'll have to live with.
Since you have a convex quadrilateral, there's another approach. Pick any three vertices and compute the barycentric coordinates of the point and of the fourth vertex with respect to the triangle formed by the three chosen vertices. If the barycentric coordinates of the point are all positive and all less than the barycentric coordinates of the fourth vertex, then the point is inside the quadrilateral.
P.S. Just found a nice page here that lists quite a number of strategies. Some of them are very interesting.
You need to use winding, or the ray trace method.
With winding, you can determine whether any point is inside any shape built with line segments.
Basically, you take the cross product of each line segment with the point, then add up all the results. That's the way I did it to decide if a star was in a constellation, given a set of constellation lines. I can see that there are other ways..
http://en.wikipedia.org/wiki/Point_in_polygon
There must be some code for this in a few places.
It is MUCH easier to see if a point lies within a triangle.
Any quadrilateral can be divided into two triangles.
If the point is in any of the two triangles that comprise the quadrilateral, then the point is inside the quadrilateral.

What is the math behind this ray-like animation?

I have unobfuscated and simplified this animation into a jsfiddle available here. Nevertheless, I still don't quite understand the math behind it.
Does someone have any insight explaining the animation?
Your fiddle link wasn't working for me due to a missing interval speed, should be using getElementById too (just because it works in Internet Explorer doesn't make it cross-browser).
Here, I forked it, use this one instead:
http://jsfiddle.net/spechackers/hJhCz/
I have also cleaned up the code in your first link:
<pre id="p">
<script type="text/javascript">
var charMap=['p','.'];
var n=0;
function myInterval()
{
n+=7;//this is the amount of screen to "scroll" per interval
var outString="";
//this loop will execute exactly 4096 times. Once for each character we will be working with.
//Our display screen will consist of 32 lines or rows and 128 characters on each line
for(var i=64; i>0; i-=1/64)
{
//Note mod operations can result in numbers like 1.984375 if working with non-integer numbers like we currently are
var mod2=i%2;
if(mod2==0)
{
outString+="\n";
}else{
var tmp=(mod2*(64/i))-(64/i);//a number between 0.9846153846153847 and -4032
tmp=tmp+(n/64);//still working with floating points.
tmp=tmp^(64/i);//this is a bitwise XOR operation. The result will always be an integer
tmp=tmp&1;//this is a bitwise AND operation. Basically we just want to know if the first bit is a 1 or 0.
outString+=charMap[tmp];
}
}//for
document.getElementById("p").innerHTML=outString;
}
myInterval();
setInterval(myInterval,64);
</script>
</pre>
The result of the code in the two links you provided are very different from one another.
However the logic in the code is quite similar. Both use a for-loop to loop through all the characters, a mod operation on a non-integer number, and a bitwise xor operation.
How does it all work, well basically all I can tell you is to pay attention to the variables changing as the input and output change.
All the logic appears to be some sort of bitwise cryptic way to decide which of 2 characters or a line break to add to the page.
I don't quite follow it myself from a calculus or trigonometry sort of perspective.
Consider that each line, as it sweeps across the rectangular area, is actually a rotation of (4?) lines about a fixed origin.
The background appears to "move" according to optical illusion. What actually happens is that the area in between the sweep lines is toggling between two char's as the lines rotate through them.
Here is the rotation eq in 2 dimensions:
first, visualize an (x,y) coordinate pair in one of the lines, before and after rotation (motion):
So, you could make a collection of points for each line and rotate them through arbitrarily sized angles, depending upon how "smooth" you want the animation.
The answer above me looks at the whole plane being transformed with the given formulae.
I tried to simplify it here -
The formula above is a trigonometric equation for rotation it is more simply solved
with a matrix.
x1 is the x coordinate before the the rotation transformation (or operator) acts.
same for y1. say the x1 = 0 and y1 = 1. these are the x,y coordinates of of the end of the
vector in the xy plane - currently your screen. if you plug any angle you will get new
coordinates with the 'tail' of the vector fixes in the same position.
If you do it many times (number of times depends on the angle you choose) you will come back to 0 x = 0 and y =1.
as for the bitwise operation - I don't have any insight as for why exactly this was used.
each iteration there the bitwise operation acts to decide if the point the plane will be drawn or not. note k how the power of k changes the result.
Further reading -
http://en.wikipedia.org/wiki/Linear_algebra#Linear_transformations
http://www.youtube.com/user/khanacademy/videos?query=linear+algebra

Click detection in a 2D isometric grid?

I've been doing web development for years now and I'm slowly getting myself involved with game development and for my current project I've got this isometric map, where I need to use an algorithm to detect which field is being clicked on. This is all in the browser with Javascript by the way.
The map
It looks like this and I've added some numbers to show you the structure of the fields (tiles) and their IDs. All the fields have a center point (array of x,y) which the four corners are based on when drawn.
As you can see it's not a diamond shape, but a zig-zag map and there's no angle (top-down view) which is why I can't find an answer myself considering that all articles and calculations are usually based on a diamond shape with an angle.
The numbers
It's a dynamic map and all sizes and numbers can be changed to generate a new map.
I know it isn't a lot of data, but the map is generated based on the map and field sizes.
- Map Size: x:800 y:400
- Field Size: 80x80 (between corners)
- Center position of all the fields (x,y)
The goal
To come up with an algorithm which tells the client (game) which field the mouse is located in at any given event (click, movement etc).
Disclaimer
I do want to mention that I've already come up with a working solution myself, however I'm 100% certain it could be written in a better way (my solution involves a lot of nested if-statements and loops), and that's why I'm asking here.
Here's an example of my solution where I basically find a square with corners in the nearest 4 known positions and then I get my result based on the smallest square between the 2 nearest fields. Does that make any sense?
Ask if I missed something.
Here's what I came up with,
function posInGrid(x, y, length) {
xFromColCenter = x % length - length / 2;
yFromRowCenter = y % length - length / 2;
col = (x - xFromColCenter) / length;
row = (y - yFromRowCenter) / length;
if (yFromRowCenter < xFromColCenter) {
if (yFromRowCenter < (-xFromColCenter))--row;
else++col;
} else if (yFromRowCenter > xFromColCenter) {
if (yFromRowCenter < (-xFromColCenter))--col;
else++row;
}
return "Col:"+col+", Row:"+row+", xFC:"+xFromColCenter+", yFC:"+yFromRowCenter;
}
X and Y are the coords in the image, and length is the spacing of the grid.
Right now it returns a string, just for testing.. result should be row and col, and those are the coordinates I chose: your tile 1 has coords (1,0) tile 2 is(3,0), tile 10 is (0,1), tile 11 is (2,1). You could convert my coordinates to your numbered tiles in a line or two.
And a JSFiddle for testing http://jsfiddle.net/NHV3y/
Cheers.
EDIT: changed the return statement, had some variables I used for debugging left in.
A pixel perfect way of hit detection I've used in the past (in OpenGL, but the concept stands here too) is an off screen rendering of the scene where the different objects are identified with different colors.
This approach requires double the memory and double the rendering but the hit detection of arbitrarily complex scenes is done with a simple color lookup.
Since you want to detect a cell in a grid there are probably more efficient solutions but I wanted to mention this one for it's simplicity and flexibility.
This has been solved before, let me consult my notes...
Here's a couple of good resources:
From Laserbrain Studios, The basics of isometric programming
Useful article in the thread posted here, in Java
Let me know if this helps, and good luck with your game!
This code calculates the position in the grid given the uneven spacing. Should be pretty fast; almost all operations are done mathematically, using just one loop. I'll ponder the other part of the problem later.
def cspot(x,y,length):
l=length
lp=length+1
vlist = [ (l*(k%2))+(lp*((k+1)%2)) for k in range(1,y+1) ]
vlist.append(1)
return x + sum(vlist)

Categories

Resources