How to know new co-ordinates after rotation in processing 2 - rotation

I have a sketch where I am using several images. One of the images is being translated and rotated.
After PopMatrix how do I know the new position (X.Y) of image that has been moved around ?

You have to use modelX() and modelY(). See the example below, which draws ellipses instead of images:
void setup(){
size(600, 600, P2D);
ellipseMode(CENTER);
pushMatrix();
translate(width/2, height/2);
rotate(1.23);
int x1 = 100, y1 = 100;
ellipse(x1, y1, 10, 10);
// store translated / rotated coordinates
float x2 = modelX(x1, y1, 0);
float y2 = modelY(x1, y1, 0);
popMatrix();
// draw red dot with stored coordinates
stroke(255, 0, 0);
ellipse(x2, y2, 2, 2);
}

Related

Processing Square Stacking loop

This is my first time writing here so i'll be direct, i've been trying to recreate this image:
and so far all the code i've got is:
void setup() {
size(500, 500);
}
void draw() {
rectMode(CENTER);
recta();
}
void recta() {
noFill();
int a = 10;
int y = 250;
for (int x = 0; x<20; x++) {
pushMatrix();
translate(y, y);
rect(0, 0, a, a);
popMatrix();
rotate(radians(2.0*PI));
stroke(0, 0, 0);
a= a - 20;
}
}
And i have no idea what to do next since this is what i get from it:
So i'd like to ask for help on how to get the same result as the image.
You are so close !
You're absolutely on the right track using pushMatrix()/popMatrix() to isolate coordinate systems, however you might have accidentally placed the rotation after popMatrix() which defeats the purpose. You probably meant to for each square to have an independent rotation from each other and not accumulate 2 * PI to the global rotation.
The other catch is that you're rotating by the same angle (2 * PI) for each iteration in your for loop and that rotation is 360 degrees so even if you fix rotation like this:
pushMatrix();
translate(y, y);
rotate(radians(2.0*PI));
rect(0, 0, a, a);
popMatrix();
you'll get a scaling effect:
(Minor note 2.0 * PI already exists in Processing as the TWO_PI constant)
To get that spiral looking effect is to increment the angle for each iteration (e.g. x = 0, rotation = 0, x = 1, rotation = 5, x = 2, rotation = 10, etc.). The angle increment is totally up to you: depending on how you map the x increment to a rotation angle angle you'll get a tighter or looser spiral.
Speaking of mapping, Processing has a map() function which makes it super easy to map from one range of numbers (let's say x from 0 to 19) to another (let's say 0 radians to PI radians):
for (int x = 0; x < 20; x++) {
pushMatrix();
translate(y, y);
rotate(map(x, 0, 19, 0, PI));
rect(0, 0, a, a);
popMatrix();
a = a - 20;
}
Here's a basic sketch based on your code:
int a = 10;
int y = 250;
void setup() {
size(500, 500);
rectMode(CENTER);
noFill();
background(255);
recta();
}
void recta() {
for (int x = 0; x < 20; x++) {
pushMatrix();
translate(y, y);
rotate(map(x, 0, 19, 0, PI));
rect(0, 0, a, a);
popMatrix();
a = a - 20;
}
}
I've removed draw() because it was rendering the same frame without any change: drawing once in setup() achieves the same visual effect using less CPU/power.
You can use draw(), but might as add some interactivity or animation to explore shapes. Here's a tweaked version of the above with comments:
int y = 250;
void setup() {
size(500, 500);
rectMode(CENTER);
noFill();
}
void draw(){
background(255);
recta();
}
void recta() {
// map mouse X position to -180 to 180 degrees (as radians)
float maxAngle = map(mouseX, 0, width, -PI, PI);
// reset square size
int a = 10;
// for each square
for (int x = 0; x < 20; x++) {
// isolate coordinate space
pushMatrix();
// translate first
translate(y, y);
// then rotate: order matters
// map x value to mouse mapped maximum rotation angle
rotate(map(x, 0, 19, 0, maxAngle));
// render the square
rect(0, 0, a, a);
popMatrix();
// decrease square size
a = a - 20;
}
}
Remember transformation order matters (e.g. translate() then rotate() would produce different effects compared to rotate() then translate()). Have fun!

How to manually apply matrix stack to coordinates in processing

In processing, when you apply a matrix transformation, you can draw on your canvas without worrying of the "true" position of your x y coordinate.
I thought that by the same logic, I could copy a section of the canvas by using ParentApplet.get(x, y, width, height) and that it would automatically shift the x and y, but it does not, it uses the coordinates as raw inputs without applying the matrix stack to it.
So the easiest way I see to deal with the problem would be to manually apply the matrix stack to my x, y, width, height values and using the results as input of get(). But I cannot find such a function, does one exist ?
EDIT : As requested, Here's an example of my problem
So the objective here is to draw a simple shape, copy it and paste it. Without translate, there is no problem:
void settings(){
size(500, 500);
}
void draw() {
background(255);
// Fancy rectangle for visibility
fill(255, 0 ,0);
rect(0, 0, 100, 100);
fill(0, 255, 0);
rect(20, 20, 60, 60);
// copy rectangle and paste it elsewhere
PImage img = get(0, 0, 101, 101);
image(img, 200, 200);
}
Now if I applied a translate matrix before drawing the shape, I wish that I could use the same get() code to copy the exact same drawing:
void settings(){
size(500, 500);
}
void draw() {
background(255);
pushMatrix();
translate(10, 10);
// Fancy rectangle for visibility
fill(255, 0 ,0);
rect(0, 0, 100, 100);
fill(0, 255, 0);
rect(20, 20, 60, 60);
// copy rectangle and paste it elsewhere
PImage img = get(0, 0, 101, 101);
image(img, 200, 200);
popMatrix();
}
But it doesn't work that way, The get(0, 0, ..) doesn't use the current transformation matrix to copy pixels from origin (10, 10):
Can you please provide a few more details.
It is possible to manipulate coordinate systems using pushMatrix()/PopMatrix() and you can go further and manually multiply matrices and vectors.
The part that is confusing is that you're calling get(x,y,width,height) but no showing how you render the PImage section. It's hard to guess the matrix stack you're mentioning. Can you post an example snippet ?
If you render it at the same x,y you call get() with it should render with the same x,y shift:
size(640, 360);
noFill();
strokeWeight(9);
PImage placeholderForPGraphics = loadImage("https://processing.org/examples/moonwalk.jpg");
image(placeholderForPGraphics, 0, 0);
int x = 420;
int y = 120;
int w = 32;
int h = 48;
// visualise region of interest
rect(x, y, w, h);
// grab the section sub PImage
PImage section = placeholderForPGraphics.get(x, y, w, h);
//filter the section to make it really standout
section.filter(THRESHOLD);
// display section at same location
image(section, x, y);
Regarding the matrix stack, you can call getMatrix() which will return a PMatrix2D if you're in 2D mode (otherwise a PMatrix3D). This is a copy of the current matrix stack at the state you've called it (any prior operations will be "baked" into this one).
For example:
PMatrix m = g.getMatrix();
printArray(m.get(new float[]{}));
(g.printMatrix() should be easier to print to console, but you need to call getMatrix() if you need an instance to manipulate)
Where g is your PGraphics instance.
You can then manipulate it as you like:
m.translate(10, 20);
m.rotate(radians(30));
m.scale(1.5);
Remember to call applyMatrix() it when you're done:
g.applyMatrix(m);
Trivial as it may be I hope this modified version of the above example illustrates the idea:
size(640, 360);
noFill();
strokeWeight(9);
// get the current transformation matrix
PMatrix m = g.getMatrix();
// print to console
println("before");
g.printMatrix();
// modify it
m.translate(160, 90);
m.scale(0.5);
// apply it
g.applyMatrix(m);
// print applied matrix
println("after");
g.printMatrix();
PImage placeholderForPGraphics = loadImage("https://processing.org/examples/moonwalk.jpg");
image(placeholderForPGraphics, 0, 0);
int x = 420;
int y = 120;
int w = 32;
int h = 48;
// visualise region of interest
rect(x, y, w, h);
// grab the section sub PImage
PImage section = placeholderForPGraphics.get(x, y, w, h);
//filter the section to make it really standout
section.filter(THRESHOLD);
// display section at same location
image(section, x, y);
Here's another example making a basic into PGraphics using matrix transformations:
void setup(){
size(360, 360);
// draw something manipulating the coordinate system
PGraphics pg = createGraphics(360, 360);
pg.beginDraw();
pg.background(0);
pg.noFill();
pg.stroke(255, 128);
pg.strokeWeight(4.5);
pg.rectMode(CENTER);
pg.translate(180,180);
for(int i = 0 ; i < 72; i++){
pg.rotate(radians(5));
pg.scale(0.95);
//pg.rect(0, 0, 320, 320, 32, 32, 32, 32);
polygon(6, 180, pg);
}
pg.endDraw();
// render PGraphics
image(pg, 0, 0);
}
This is overkill: the same effect could have been drawn much simpler, however the focus in on calling get() and using transformation matrices. Here a modified iteration showing the same principle with get(x,y,w,h), then image(section,x,y):
void setup(){
size(360, 360);
// draw something manipulating the coordinate system
PGraphics pg = createGraphics(360, 360);
pg.beginDraw();
pg.background(0);
pg.noFill();
pg.stroke(255, 128);
pg.strokeWeight(4.5);
pg.rectMode(CENTER);
pg.translate(180,180);
for(int i = 0 ; i < 72; i++){
pg.rotate(radians(5));
pg.scale(0.95);
//pg.rect(0, 0, 320, 320, 32, 32, 32, 32);
polygon(6, 180, pg);
}
pg.endDraw();
// render PGraphics
image(pg, 0, 0);
// take a section of PGraphics instance
int w = 180;
int h = 180;
int x = (pg.width - w) / 2;
int y = (pg.height - h) / 2;
PImage section = pg.get(x, y, w, h);
// filter section to emphasise
section.filter(INVERT);
// render section at sampled location
image(section, x, y);
popMatrix();
}
void polygon(int sides, float radius, PGraphics pg){
float angleIncrement = TWO_PI / sides;
pg.beginShape();
for(int i = 0 ; i <= sides; i++){
float angle = (angleIncrement * i) + HALF_PI;
pg.vertex(cos(angle) * radius, sin(angle) * radius);
}
pg.endShape();
}
Here's a final iteration re-applying the last transformation matrix in an isolated coordinate space (using push/pop matrix calls):
void setup(){
size(360, 360);
// draw something manipulating the coordinate system
PGraphics pg = createGraphics(360, 360);
pg.beginDraw();
pg.background(0);
pg.noFill();
pg.stroke(255, 128);
pg.strokeWeight(4.5);
pg.rectMode(CENTER);
pg.translate(180,180);
for(int i = 0 ; i < 72; i++){
pg.rotate(radians(5));
pg.scale(0.95);
//pg.rect(0, 0, 320, 320, 32, 32, 32, 32);
polygon(6, 180, pg);
}
pg.endDraw();
// render PGraphics
image(pg, 0, 0);
// take a section of PGraphics instance
int w = 180;
int h = 180;
int x = (pg.width - w) / 2;
int y = (pg.height - h) / 2;
PImage section = pg.get(x, y, w, h);
// filter section to emphasise
section.filter(INVERT);
// print last state of the transformation matrix
pg.printMatrix();
// get the last matrix state
PMatrix m = pg.getMatrix();
// isolate coordinate space
pushMatrix();
//apply last PGraphics matrix
applyMatrix(m);
// render section at sampled location
image(section, x, y);
popMatrix();
save("state3.png");
}
void polygon(int sides, float radius, PGraphics pg){
float angleIncrement = TWO_PI / sides;
pg.beginShape();
for(int i = 0 ; i <= sides; i++){
float angle = (angleIncrement * i) + HALF_PI;
pg.vertex(cos(angle) * radius, sin(angle) * radius);
}
pg.endShape();
}
This is an extreme example, as 0.95 downscale is applied 72 times, hence a very small image is rendered. Also notice the rotation is incremented.
Update Based on your update snippet it seems the confusion is around pushMatrix() and get().
In your scenario, pushMatrix()/translate() will offset the local coordinate sytem: that is where elements are drawn.
get() is called globally and uses absolute coordinates.
If you're only using translation, you can simply store the translation coordinates and re-use them to sample from the same location:
int sampleX = 10;
int sampleY = 10;
void settings(){
size(500, 500);
}
void draw() {
background(255);
pushMatrix();
translate(sampleX, sampleY);
// Fancy rectangle for visibility
fill(255, 0 ,0);
rect(0, 0, 100, 100);
fill(0, 255, 0);
rect(20, 20, 60, 60);
// copy rectangle and paste it elsewhere
PImage img = get(sampleX, sampleY, 101, 101);
image(img, 200, 200);
popMatrix();
}
Update
Here are a couple more examples on how to compute, rather than hard code the translation value:
void settings(){
size(500, 500);
}
void setup() {
background(255);
pushMatrix();
translate(10, 10);
// Fancy rectangle for visibility
fill(255, 0 ,0);
rect(0, 0, 100, 100);
fill(0, 255, 0);
rect(20, 20, 60, 60);
// local to global coordinate conversion using PMatrix
// g is the global PGraphics instance every PApplet (sketch) uses
PMatrix m = g.getMatrix();
printArray(m.get(null));
// the point in local coordinate system
PVector local = new PVector(0,0);
// multiply local point by transformation matrix to get global point
// we pass in null to get a new PVector instance: you can make this more efficient by allocating a single PVector ad re-using it instead of this basic demo
PVector global = m.mult(local,null);
// copy rectangle and paste it elsewhere
println("local",local,"->global",global);
PImage img = get((int)global.x, (int)global.y, 101, 101);
image(img, 200, 200);
popMatrix();
}
To calculate the position of a vector based on a transformation matrix, simply multiply the vector by that matrix. Very roughly speaking what's what happens with push/pop matrix (a transformation matrix is used for each push/pop stack, which is then multiplied all the way up the global coordinate system). (Notice the comment on efficienty/pre-allocating matrices and vectors as well).
This will be more verbose in terms of code and may need a bit of planning if you're using a lot of nested transformations, however you have finer control of which transformations you choose to use.
A simpler solution may be to switch to the P3D OpenGL renderer which allows you use screenX(), screenY() to do this conversion. (Also checkout modelX()/modelY())
void settings(){
size(500, 500, P3D);
}
void draw() {
background(255);
pushMatrix();
translate(10, 10);
// Fancy rectangle for visibility
fill(255, 0 ,0);
rect(0, 0, 100, 100);
fill(0, 255, 0);
rect(20, 20, 60, 60);
// local to global coordinate conversion using modelX,modelY
float x = screenX(0, 0, 0);
float y = screenY(0, 0, 0);
println(x,y);
PImage img = get((int)x, (int)y, 101, 101);
image(img, 200, 200);
popMatrix();
}
Bare in mind that you want to grab a rectangle which simply has translation applied. Since get() won't take rotation/scale into account, for more complex cases you may want to convert local to global coordinates of not just the top left point, but also the bottom right one with an offset. The idea is to compute the larger bounding box (with no rotation) around the transformed box so when you call get() the whole area of interest is returned (not just a clipped section).

How to add a gradient in a Bezier curve?

I have drawn curves that denote the customer country and the country where he is headed for a trip in a map.
But I could not add a gradient so that the lines would denote the said information and gives this random color between two colors at random. Here's what I tried.
int steps = 10;
noFill();
//stroke(#5A38FA, 50);
strokeWeight(1);
for(int i=0; i<steps; i++) {
strokeWeight(1);
noFill();
stroke(lerpColor(#31B5E8, #F0E62E, (float)i/steps));
bezier(locationX, locationY, locationX+random(15, 50), locationY+random(13,50), customerLocationX+random(15, 30), customerLocationY+random(15, 70), customerLocationX, customerLocationY);
}
You can decompose a bezier curve into points using the bezierPoint()method and then draw straight line segments between successive points, specifying the colour for each individual line segment (meanwhile gradually lerping the colour of course).
I've produced a method which can do that in the code example below.
Additionally, with the method, you can specify the curve's magnitude (curve) and the direction of the curve (dir); the method calculates the bezier control point using the point on a line perpendicular to the midpoint between the start point (head) and end point (tail).
void setup() {
size(500, 500);
smooth(4);
noLoop();
redraw();
strokeWeight(5);
noFill();
}
void draw() {
background(35);
drawCurve(new PVector(50, 50), new PVector(456, 490), #31B5E8, #F0E62E, 50, -1);
drawCurve(new PVector(150, 75), new PVector(340, 410), #B9FF00, #FF00C5, 150, 1);
drawCurve(new PVector(200, 480), new PVector(480, 30), #007CFF, #89CA7F, 100, 1);
}
void drawCurve(PVector head, PVector tail, color headCol, color tailCol, float curve, int curveDir) {
final float theta2 = angleBetween(tail, head);
final PVector midPoint = new PVector((head.x + tail.x) / 2,
(head.y + tail.y) / 2);
final PVector bezierCPoint = new PVector(midPoint.x + (sin(-theta2) * (curve * 2 * curveDir)),
midPoint.y + (cos(-theta2) * (curve * 2 * curveDir)));
PVector point = head.copy();
for (float t=0; t<=1; t+=0.025) {
float x1 = bezierPoint(head.x, bezierCPoint.x, bezierCPoint.x, tail.x, t);
float y1 = bezierPoint(head.y, bezierCPoint.y, bezierCPoint.y, tail.y, t);
PVector pointB = new PVector(x1, y1);
stroke(lerpColor(headCol, tailCol, t));
line(point.x, point.y, pointB.x, pointB.y);
point = pointB.copy();
}
}
static float angleBetween(PVector tail, PVector head) {
float a = PApplet.atan2(tail.y - head.y, tail.x - head.x);
if (a < 0) {
a += PConstants.TWO_PI;
}
return a;
}
Result:

3D Baton Circles move around a Sun

How do I use translate and rotate to position spheres and lines on the canvas and also rotate the entire scene with Java Processing?
I need to be able to do this so that I can:
Create a class for a 3D baton which contains two equal size spheres and a line connecting the centers of the two spheres. The Baton class must have the following field variables:
float x, y, z; // the x, y, z coordinates of the center of one baton sphere
// the other baton sphere should be (-x, -y, -z)
float angle; // rotation angle
float speed; //rotational speed
float radius; //radius of the baton sphere
In the main tab of the sketch I need to create a scene that contains the following:
A yellow sphere with radius 50 at the center of the window. The yellow sphere doesn’t move.
6 batons rotating about the y axis passing through the yellow sphere.
Each baton rotates at a random speed between 0.01 and 0.04.
All batons have different distances from the center of the yellow sphere.
The radius of each baton sphere is a random number between 15 and 30.
3D Batons Picture
This is my code:
Baton[] batons;
void setup() {
size(600, 600);
batons = new Baton[4];
for(int i = 0; i < batons.length; i++)
batons[i] = new Baton(100, 100, 100, 45, 2, 25, 2);
}
void draw() {
background(255);
stroke(0);
translate(width/2, height/2);
fill(255, 200, 50);
sphere(50);
for(int i = 0; i < batons.length; i++) {
batons[i].update();
batons[i].display();
}
}
class Baton {
float x;
float y;
float z;
float angle;
float speed;
float radius;
float theta;
Baton(float x, float y, float z, float angle, float speed, float radius, float theta) {
this.x = x;
this.y = y;
this.z = y;
this.angle = angle;
this.speed = speed;
this.radius = radius;
theta = 0;
}
void update() {
theta = theta + speed;
}
void display() {
pushMatrix();
rotate(theta);
translate(radius/2, 0);
fill(51, 51, 51);
noStroke();
sphere(radius);
popMatrix();
line(x, y, -x, -y);
pushMatrix();
rotate(theta);
translate(radius/2, 0);
fill(51, 51, 51);
noStroke();
sphere(radius);
popMatrix();
}
}
The Baton has to go through the Sun that is in the middle. This means that the two circles and the line that connects it has to rotate around the Sun. To explain easier the line will go through the Sun and rotate with the two Circles. See the picture link above.
The main thing that makes your code render differently than the image you have attached is that the Baton objects are placed at the center of the canvas and end up being hidden by the sphere at the center.
Here I have moved the Baton spheres out away from the center and have slowed down the frameRate and speed so that it is easier to see how they are moving.
Baton[] batons;
void setup() {
size(600, 600, P3D);
batons = new Baton[4];
frameRate(1); // slowed down the frame rate to 1 frame per second
for(int i = 0; i < batons.length; i++){
// changed speed from 2 to 0.1 so that the batons move in smaller increments
batons[i] = new Baton(100, 100, 100, 45, 0.1, 25, 2);
}
}
void draw() {
background(255);
stroke(0);
translate(width/2, height/2);
fill(255, 200, 50);
sphere(50);
for(int i = 0; i < batons.length; i++) {
batons[i].update();
batons[i].display();
}
}
class Baton {
float x;
float y;
float z;
float angle;
float speed;
float radius;
float theta;
Baton(float x, float y, float z, float angle, float speed, float radius, float theta) {
this.x = x;
this.y = y;
this.z = y;
this.angle = angle;
this.speed = speed;
this.radius = radius;
theta = 0;
}
void update() {
theta = theta + speed;
}
void display() {
pushMatrix();
// since we want the entire configuration to rotate we will rotate the entire canvas
rotate(theta);
// for a more interesting rotation we could do this instead:
// rotateX(theta);
// rotateY(theta);
// rotateZ(theta);
float distanceBetweenBatonSpheres = radius + 300;
translate(distanceBetweenBatonSpheres/2, 0);
fill(0, 200, 200);
sphere(radius);
// now we undo the previous translate and also move back out to the other side of the central sphere
translate(distanceBetweenBatonSpheres/-1.0, 0);
sphere(radius);
// and finally.. draw a line to connect the two spheres
line(0,0,distanceBetweenBatonSpheres, 0);
popMatrix();
}
}
Notice how we rotate the entire canvas so that the configuration of spheres rotates as a body along with the line that connects the baton spheres.
Also see the comments about making the sketch more interesting by rotating in the x, y and z directions.

Processing - Line in direction of mouse pointer

I am trying to achieve an effect like the image below
In my code, I managed to create this effect but in repeating the effect it seems to multiply inwards on itself. Could anyone help me to make my code achieve the effect in the image above?
void setup(){
size(500,500);
frameRate(60);
ellipseMode(CENTER);
smooth();
loop();
}
void draw() {
background(#ffffff);
//border
strokeWeight(3);
fill(255);
arc(50, 50, 50, 50, -PI, -PI / 2);
fill(255);
arc(450, 450, 50, 50, 0, PI / 2.0);
line(25, 50, 25, 475);
line(25, 475, 450, 475);
line(475, 450, 475, 25);
line(475, 25, 135, 25);
fill(0);
text("MAGNETS", 60, 30);
//Lines
for(int i=0; i<3; i++){
drawMagnet();
}
}
float angle = 0;
int x = 75;
int y = 75;
float tAngle = 0;
float easing = 0.1f;
void drawMagnet(){
int l = 10; //length
angle = atan2( mouseY - y, mouseX - x);
float dir = (angle - tAngle) / TWO_PI;
dir -= round(dir);
dir *= TWO_PI;
tAngle += dir * easing;
stroke(0);
translate(x, y);
rotate(tAngle);
line(-l, 0, l, 0);
}
Your rotations and translations are stacking, which is causing your problem. To fix this, you might do something like this:
pushMatrix();
translate(x, y);
rotate(tAngle);
line(-l, 0, l, 0);
popMatrix();
Here I'm using the pushMatrix() and popMatrix() functions so your rotations and translations don't stack.
But then all of your lines are at the same x,y location. So they'll all have the same angle towards the mouse position.
You're using the translate() function to draw them in different locations, but that doesn't change their underlying "model" position.
Similar to my answer to this question, you need to either base your calculations off the screen position of the lines (using the screenX() and screenY() functions), or you need to stop relying on translate() to move your lines around and calculate their positions directly.

Resources