Creating a view with shadow in a Processing game - processing

I am writing a game for school project using Processing. I am currently dealing with a player's field of view. The player's field of view is basically a circle, but I would like the view to be blocked if there is an obstacle in front, meaning that you can't see the things behind the obstacle. The below image is the current results I have.
The link to the image
My code: http://pastie.org/10854654
The method I used is to go through every pixel in the player's field of view starting from the center, picking a path towards the circumference. As I searched outwards, if an obstacle is found on the path, I then draw a black line on the rest of the path. Changing the direction of the path degree by degree, eventually covering the whole circle.
//Draw a circle field of view.
int[][] collisionMap = map.getCollisionMap();
//Use a lot of small rectangle to cover the full map except of the circle field of view.
mainapplet.fill(0, 0, 0, 128);
for(int i = 0; i <= MyApplet.width; i++ ){
for(int j = 0; j <= MyApplet.height; j++ ){
if(mainapplet.dist(playerx, playery, i, j) > FieldOfView)
mainapplet.rect(i, j, 1, 1);
}
}
//Scan the circle field of view. If there is collision , draw a line to cover the area ,which means that the area is invisible.
mainapplet.stroke(0, 0, 0, 128);
mainapplet.strokeWeight(5);
for(float i = 0; i < 360; i+=1) {
for(float j = 0; j < FieldOfView ; j++ ){
float x = j * mainapplet.cos( mainapplet.radians(i) );
float y = j * mainapplet.sin( mainapplet.radians(i) );
if(collisionMap[player.getX() + (int)x ][player.getY() + (int)y ] == 1){
mainapplet.line(playerx + x, playery + y,
playerx + (FieldOfView-1)* mainapplet.cos( mainapplet.radians(i) ),
playery + (FieldOfView-1)* mainapplet.sin( mainapplet.radians(i) )
);
break;
}
}
}
collisionMap is a 2D array with 0s and 1s, "1" denoting that an obstacle is present at the location.
However, I find this method inefficient, therefore, causing lag. Is there a better way to do this? Or maybe there are already written tools that I can use?

What you're talking about is called 2d shadow mapping. It's not a trivial topic, but there are a ton of resources on google. I highly recommend reading up on them, because they'll explain it much better than I can.
But I did find this sketch on OpenProcessing which does what you describe. The full code is available at that link, but the pertinent bit seems to be this function:
void drawShadow() {
PVector tmp;
PVector m = new PVector(mouseX, mouseY); //mouse vector
fill(0);
stroke(0);
for (int i=0; i < vertCnt; i++) {
beginShape();
PVector v1 = p[i]; //current vertex
PVector v2 = p[i==vertCnt-1?0:i+1]; //"next" vertex
vertex(v2.x, v2.y);
vertex(v1.x, v1.y);
//current shadow vertex
tmp = PVector.sub(v1, m);
tmp.normalize();
tmp.mult(5000); //extend well off screen
tmp.add(v1); //true up position
vertex(tmp.x, tmp.y);
//"next" shadow vertex
tmp = PVector.sub(v2, m);
tmp.normalize();
tmp.mult(5000); //extend well off screen
tmp.add(v2); //true up position
vertex(tmp.x, tmp.y);
endShape(CLOSE);
}
}
But honestly the best thing you can do is google "processing shadow mapping" and spend some time reading through the results. This is a huge topic that's a bit too broad for a single Stack Overflow question.

Related

Why is the floor in my raycaster seemingly "misaligned"?

I have been working on a doom/wolfenstein style raycaster for a while now. I implemented the "floor raycasting" to the best of my ability, roughly following a well known raycaster tutorial. It almost works, but the floor tiles seem slightly bigger than they should be, and they don't "stick", as in they don't seem to align properly and they slide slightly as the player moves/rotates. Additionally, the effect seems worsened as the FOV is increased. I cannot figure out where my floor casting is going wrong, so any help is appreciated.
Here is a (crappy) gif of the glitch happening
Here is the most relevant part of my code:
void render(PVector pos, float dir) {
ArrayList<FloatList> dists = new ArrayList<FloatList>();
for (int i = 0; i < numColumns; i++) {
float curDir = atan((i - (numColumns/2.0)) / projectionDistance) + dir;
// FloatList because it returns a few pieces of data
FloatList curHit = cast(pos, curDir);
// normalize distances with cos
curHit.set(0, curHit.get(0) * cos(curDir - dir));
dists.add(curHit);
}
screen.beginDraw();
screen.background(50);
screen.fill(0, 30, 100);
screen.noStroke();
screen.rect(0, 0, screen.width, screen.height/2);
screen.loadPixels();
PImage floor = textures.get(4);
// DRAW FLOOR
for (int y = screen.height/2 + 1; y < screen.height; y++) {
float rowDistance = 0.5 * projectionDistance / ((float)y - (float)rY/2);
// leftmost and rightmost (on screen) floor positions
PVector left = PVector.fromAngle(dir - fov/2).mult(rowDistance).add(p.pos);
PVector right = PVector.fromAngle(dir + fov/2).mult(rowDistance).add(p.pos);
// current position on the floor
PVector curPos = left.copy();
PVector stepVec = right.sub(left).div(screen.width);
float b = constrain(map(rowDistance, 0, maxDist, 1, 0), 0, 1);
for (int x = 0; x < screen.width; x++) {
color sample = floor.get(floor((curPos.x - floor(curPos.x)) * floor.width), floor((curPos.y - floor(curPos.y)) * floor.height));
screen.pixels[x + y*screen.width] = color(red(sample) * b, green(sample) * b, blue(sample) * b);
curPos.add(stepVec);
}
}
updatePixels();
}
If anyone wants to look at the full code or has any questions, ask away.
Ok, I seem to have found a "solution". I will be the first to admit that I do not understand why it works, but it does work. As per my comment above, I noticed that my rowDistance variable was off, which caused all of the problems. In desperation, I changed the FOV and then hardcoded the rowDistance until things looked right. I plotted the ratio between the projectionDistance and the numerator of the rowDistance. I noticed that it neatly conformed to a scaled cos function. So after some simplification, here is the formula I came up with:
float rowDistance = (rX / (4*sin(fov/2))) / ((float)y - (float)rY/2);
where rX is the width of the screen in pixels.
If anyone has an intuitive explanation as to why this formula makes sense, PLEASE enlighten me. I hope this helps anyone else who may have this problem.

TileMap color is changing depending on Camera angle [UNITY]

Currently, I'm trying to highlight tiles around the outside of the object currently being dragged. I have tilemaps attached to the same object, one is the white border around the outside of the object and the other is the green center. The issue I am having at the moment is when the camera is facing the tiles at a set angle, the green tile will seem pale and at some coordinates. However, if I move the rotation or position of the camera, the pale tile will turn back to a solid green but turn pale again at another coordinate. I've attached two photos to show an example.
And here is the code involved with the tilemap:
//Reinitialize position to match TileMap orientation;
Vector3 newVec = new Vector3(pos.x, pos.z, 0);
Vector3 bottomRightPoint = newVec + new Vector3(1, 1, 0);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
//if tile painting is the center player tile
if (i == 1 && j == 1) {
colourTileMap.color = selfTile;
colourTileMap.SetTile(Vector3Int.FloorToInt(bottomRightPoint - new Vector3(i, j, 0)), tile);
Debug.Log("selfTile" + selfTile);
}
tileMap.SetTile(Vector3Int.FloorToInt(bottomRightPoint - new Vector3(i, j, 0)), tile);
}
}
}
If you need any other information please feel free to reach out. Thanks in advance!

Processing: Efficiently create uniform grid

I'm trying to create a grid of an image (in the way one would tile a background with). Here's what I've been using:
PImage bgtile;
PGraphics bg;
int tilesize = 50;
void setup() {
int t = millis();
fullScreen(P2D);
background(0);
bgtile = loadImage("bgtile.png");
int bgw = ceil( ((float) width) / tilesize) + 1;
int bgh = ceil( ((float) height) / tilesize) + 1;
bg = createGraphics(bgw*tilesize,bgh*tilesize);
bg.beginDraw();
for(int i = 0; i < bgw; i++){
for(int j = 0; j < bgh; j++){
bg.image(bgtile, i*tilesize, j*tilesize, tilesize, tilesize);
}
}
bg.endDraw();
print(millis() - t);
}
The timing code says that this takes about a quarter of a second, but by my count there's a full second once the window opens before anything shows up on screen (which should happen as soon as draw is first run). Is there a faster way to get this same effect? (I want to avoid rendering bgtile hundreds of times in the draw loop for obvious reasons)
One way could be to make use of the GPU and let OpenGL repeat a texture for you.
Processing makes it fairly easy to repeat a texture via textureWrap(REPEAT)
Instead of drawing an image you'd make your own quad shape and instead of calling vertex(x, y) for example, you'd call vertex(x, y, u, v); passing texture coordinates (more low level info on the OpenGL link above). The simple idea is x,y would control the geometry on screen and u,v would control how the texture is applied to the geometry.
Another thing you can control is textureMode() which allows you control how you specify the texture coordinates (U, V):
IMAGE mode is the default: you use pixel coordinates (based on the dimensions of the texture)
NORMAL mode uses values between 0.0 and 1.0 (also known as normalised values) where 1.0 means the maximum the texture can go (e.g. image width for U or image height for V) and you don't need to worry about knowing the texture image dimensions
Here's a basic example based on the textureMode() example above:
PImage img;
void setup() {
fullScreen(P2D);
noStroke();
img = loadImage("https://processing.org/examples/moonwalk.jpg");
// texture mode can be IMAGE (pixel dimensions) or NORMAL (0.0 to 1.0)
// normal means 1.0 is full width (for U) or height (for V) without having to know the image resolution
textureMode(NORMAL);
// this is what will make handle tiling for you
textureWrap(REPEAT);
}
void draw() {
// drag mouse on X axis to change tiling
int tileRepeats = (int)map(constrain(mouseX,0,width), 0, width, 1, 100);
// draw a textured quad
beginShape(QUAD);
// set the texture
texture(img);
// x , y , U , V
vertex(0 , 0 , 0 , 0);
vertex(width, 0 , tileRepeats, 0);
vertex(width, height, tileRepeats, tileRepeats);
vertex(0 , height, 0 , tileRepeats);
endShape();
text((int)frameRate+"fps",15,15);
}
Drag the mouse on the Y axis to control the number of repetitions.
In this simple example both vertex coordinates and texture coordinates are going clockwise (top left, top right, bottom right, bottom left order).
There are probably other ways to achieve the same result: using a PShader comes to mind.
Your approach caching the tiles in setup is ok.
Even flattening your nested loop into a single loop at best may only shave a few milliseconds off, but nothing substantial.
If you tried to cache my snippet above it would make a minimal difference.
In this particular case, because of the back and forth between Java/OpenGL (via JOGL), as far as I can tell using VisualVM, it looks like there's not a lot of room for improvement since simply swapping buffers takes so long (e.g. bg.image()):
An easy way to do this would be to use processing's built in get(); which saves a PImage of the coordinates you pass, for example: PImage pic = get(0, 0, width, height); will capture a "screenshot" of your entire window. So, you can create the image like you already are, and then take a screenshot and display that screenshot.
PImage bgtile;
PGraphics bg;
PImage screenGrab;
int tilesize = 50;
void setup() {
fullScreen(P2D);
background(0);
bgtile = loadImage("bgtile.png");
int bgw = ceil(((float) width) / tilesize) + 1;
int bgh = ceil(((float) height) / tilesize) + 1;
bg = createGraphics(bgw * tilesize, bgh * tilesize);
bg.beginDraw();
for (int i = 0; i < bgw; i++) {
for (int j = 0; j < bgh; j++) {
bg.image(bgtile, i * tilesize, j * tilesize, tilesize, tilesize);
}
}
bg.endDraw();
screenGrab = get(0, 0, width, height);
}
void draw() {
image(screenGrab, 0, 0);
}
This will still take a little bit to generate the image, but once it does, there is no need to use the for loops again unless you change the tilesize.
#George Profenza's answer looks more efficient than my solution, but mine may take a little less modification to the code you already have.

How do only update pixels once

My pixels are updating every frame causing the effect to be re-applied to the previous frame. How can i make this effect only happen once and without using noLoop(). I just want there to be a large circle around the triangle. Please help. Thanks.
Here is the whole program. I set the frameRate to 1 so you can see the problem easier:
boolean up;
int x =-300;
int y =-300;
void setup()
{
size(600, 600);
frameRate(1);
}
void draw()
{
pushMatrix();
translate(300, 300);
float a = atan2(mouseY-300, mouseX-300);
rotate(a);
for (int i = x; i < x+width; i+=40)
for (int j = y; j < y+height; j+=40)
rect(i, j, 40, 40);
loadPixels();
for (int i = 0; i < pixels.length; i++)
{
x = i%width;
y = i/width;
color c = pixels[x+y*width];
float d = dist(x, y, width/2, height/2);
pixels[x+y*width] = color(brightness(c) - d);
}
updatePixels();
popMatrix();
fill(255, 0, 0);
triangle(280, 300, 300, 200, 320, 300);
if (up)
{
x += sin(a)*5;
y += cos(a)*5;
}
}
void keyPressed()
{
if (key=='w')up=true;
}
void keyReleased()
{
if (key=='w')up=false;
}
Re-draw everything in one frame.
Remember before you use your filter, you must undo the filter effects of the last time.
The usual ordering in your draw() function goes as follows:
Add a background / clear all the objects you added in the last frame & clearing the filter of your last frame.
Add your objects.
Lay your filter on top.
Try to refrain from doing any graphic related stuff in setup, hence it will be destroyed by this draw() function - paradigma.
This should already suffice as your answer. Quick note:
When you work with for e.g. a 3D - Shadow filter, applying the filter can take a very long time. Instead we try to store as many calculations we did on the previous frame, so we don't need to calculate everything over again. The same goes for the objects-layer. You don't want to calculate the shortest-path for a minion every frame, instead you calculate the shortest path once and only recalculate it, when something changes: Position of a box, player position, etc..
If you want just use your filter and move fluently around update your effect like this:
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
color c = pixels[x+y*width];
float d = dist(x, y, width/2, height/2);
pixels[x+y*width] = color(brightness(c) - d);
}
}
You had unnecessary calculation that consume lot of CPU resources. Redrawing background also helps to make clearer animation.
If you want generate this effect only once and then apply it. PGraphics could achieve something similar.

Processing Spacing

I'm trying to draw bears in processing, (Just simple circles), how can I get the bears equally spaced apart, and have the same space from the edge of the screen to the bears, on either side? As well as vertically.
I know this is vague, but I'm terrible at explaining things
Because you does not provide any code or example I will just tell you how to place circle in the middle of sketch.
For simplicity imagine this set up:
void setup(){
size(400, 400);
}
1) Very basic approach would be to hard code position of this circle into ellipse draw function.
ellipse(200, 200, 50, 50);
Where first two parameters are coordinates for circle center. Simple find out from size 400x400 that mid is on coord 200x200. This is bad approach and you should avoid using it.
2) Better approach would be to calculate center coord using global variables width and height
ellipse(width/2, height/2, 50, 50);
3) When you are drawing or moving more complex objects it is preferred to use some function to draw this objects always with same fixed position in our example
void draw_circle(){
ellipse(0, 0, 50, 50);
}
And just moving center of drawing using transformations so our draw function will looks like this
void draw(){
pushMatrix();
translate(width/2, height/2);
draw_circle();
popMatrix();
}
Using this you could be able to draw bears equally spaced apart and from sides.
It sounds like you want a grid of equally spaced circles. For that you just need to divide your space into a grid in the x and y directions. The simplest way to do this is to wrap the kind of thing Majlik showed inside a double loop to move from cell to cell in your 'virtual' grid. To see this more clearly, in the code below there is an extra little bit so that if you press the 'g' key (for grid) you'll see the grid cells, with a circle centered in each one. You can press any other key to make the grid go away.
You can see that each way gives the same result: inside draw() uncomment the one you want and comment out the other 2.
int nx = 4; // number of circles horizontally
int ny = 5; // number of circles vertically
int divx;
int divy;
int diameter = 40;
void setup() {
size(600, 600);
// calculate width and hegith of each cell of the grid
divx = width/nx;
divy = height/ny;
}
// 3 ways to draw a regular grid of circles
void draw() {
background(200);
// show the cell layout if the g key was typed, otherwise don't
if(key == 'g')
drawGrid();
// 1 way
for(int i = 0; i < nx; i++) {
for(int j = 0; j < ny; j++ ) {
ellipse(i * divx + divx/2, j * divy + divy/2, diameter, diameter);
}
}
// another way
// for(int i = divx/2; i < width; i += divx) {
// for(int j = divy/2; j < height; j += divy ) {
// ellipse(i, j, diameter, diameter);
// }
// }
// yet another way
// for(int i = divx/2; i < width; i += divx) {
// for(int j = divy/2; j < height; j += divy ) {
// pushMatrix();
// translate(i, j);
// ellipse(0, 0, diameter, diameter);
// popMatrix();
// }
// }
}
void drawGrid() {
// draw vertical lines
for(int i = 1; i < nx; i++) {
line(i * divx, 0, i * divx, height);
}
// draw horizontal lines
for(int j = 1; j < ny; j++ ) {
line(0, j * divy, width, j * divy);
}
}

Resources