Quantcast
Channel: Library Questions - Processing 2.x and 3.x Forum
Viewing all 2896 articles
Browse latest View live

Trigger sample causes horrible loud distortion using MINIM

$
0
0

Hello, Im trying to get a sample to trigger when the mouse passes over a movie (which then loops and enlarges) and stop when the mouse is no longer on that movie.

In the below code everything is working correctly but the sound that is heard is horribly distorted. I think this is because it is playing a new sample every frame, but I'm not sure how to prevent that. I can get the sample to play back fine in mousePressed() (outside of draw) but i don't want to use that- i want the sound to play only when the mouse passes over the movie box. If the solution is to move the "sample.trigger();" out of draw where would it go?

Im on OSX 10.10.5 and using Processing 3.02

Code is below - but be warned - turn your speakers down if u play that exact code!

Thanks.

import processing.video.*;
import ddf.minim.*;


Movie movie1;
Minim minim;
AudioSample sample;

float bx;
float by;
int boxSize;
boolean overBox = false;
float boxMax = 100;
float boxMin = 25;

void setup() {
fullScreen(2);
minim = new Minim(this);
bx = width/2;
by = height/2;
imageMode(CENTER);
boxSize = 25;

movie1 = new Movie(this, "TORCH_2_1.mov");
movie1.loop();
movie1.pause();
sample = minim.loadSample("Paper Rustle_1.mp3");
}

void movieEvent(Movie movie1) {
movie1.read();
}

 void draw() {

background(155);

if (mouseX > bx-(boxSize/2) && mouseX < bx+(boxSize/2) &&
mouseY > by-(boxSize/2) && mouseY < by+(boxSize/2)) {
overBox = true;

} else {

overBox = false;
}

if ((overBox) && (boxSize < boxMax)) {

image(movie1, bx, by,boxSize++,boxSize++);
movie1.loop();


}
if ((!overBox)&&(boxSize > boxMin)){

image(movie1, bx, by,boxSize-=3,boxSize-=3);
movie1.pause();


}
image(movie1,bx,by,boxSize,boxSize);

if (overBox) {
sample.trigger();

}

if (!overBox) {
sample.stop();

}

}

Can anybody tell me why I'm getting a null pointer on my PImage array??

$
0
0
import processing.serial.*;

import cc.arduino.*;

import static javax.swing.JOptionPane.*;
import javax.swing.JPasswordField;




final StringDict accounts = new StringDict(
  new String[] {
  "john", "tony", "amy"
  }
  , new String[] {
    "ilikedogs", "husky", "pepsi"
  }
  );

final JPasswordField pwd = new JPasswordField();

{
  println(accounts);
}
float m;

PImage startGameBackground;
PImage kitchen;
PImage dog;
float dogx=800, dogy=600;
HealthBar hb0 = new HealthBar();
boolean isWashed=false;

PImage[] images = new PImage[3];


PImage achievment2;
int val;
int stage =1;
Serial port;

//Fountain f = new Fountain();
//Ball b = new Ball(x,y,d,xs,ys);
Ball b = new Ball();


ArrayList<Ball>ballList;
boolean buttonOn = false;

final int HowLongIsItWaiting1 = 900;
int frameNum = 0;


void setup() {


  size(1800, 900);
  String comPort = "COM3";

  stage =1;
  port = new Serial(this, comPort, 9600);

  //f.fountainSetup();
  ballList = new ArrayList<Ball>();
  m = millis();

  startGameBackground = loadImage("startGameBackground.png");
  kitchen = loadImage("kitchen.png");
  dog = loadImage("washDog.png");
  startGameBackground.resize(1800, 900);
  kitchen.resize(1800, 900);
  achievment2 = loadImage("achievment2.png");
  val = port.read();

  images[0] = loadImage("washDog.png");
  images[1] = loadImage("washDog2.png");
  images[2] = loadImage("washDog3.png");

  for ( int i = 0; i < images.length; i++ )
  {
    images[i] = loadImage(i + ".png" );
  }

  frameRate(30);
}




void draw() {



  if (stage ==1) {

    background(startGameBackground);

    if (frameCount == 1)  surface.setVisible(true);


    String user = askUser();

    if (user == null)           confirmQuit();
    else if (!"".equals(user))  askPass(user);
  } else if (stage ==2) {





    background(kitchen);
    image(dog, dogx, dogy);
    hb0.draw();

    isWashed =true;

    if (mousePressed ==true) {
      float xSpeed = (float)(-3 + Math.random()*6);
      Ball b = new Ball(880, 400, 20, xSpeed, -2);

      b.dropColour = color(204, 255, 255);

      ballList.add(b);
    }


    for (int i =0; i <ballList.size(); i++) {
      Ball b2 = ballList.get(i);



      fill(b2.dropColour);
      ellipse(b2.x, b2.y, b2.diameter, b2.diameter);
      b2.move();
      //println("working");


      b2.isDead();

      if (b2.isAlive == false)
        ballList.remove(b2);








      if (hb0.value <100) {


        port.write(2);
        //delay(1000);
        //for(Ball b:ballList){
        b2.isDead();

        if (b2.isAlive == false) {
          ballList.remove(b2);
          hb0.value += .5;
          println("A ball was destroyed");
        } else {
          println("A ball survived");
        }
      }
      //} else if (hb0.value >= hb0.max) {
        frameNum++;
        frameNum %= images.length;
        image(images[frameNum], 800, 600);

        port.write(1);


        println("Here is the achievment");
        image(achievment2, 700, 100);



        if (millis()-m>HowLongIsItWaiting1) {



          exit();
        }
      }
    }
  }
}











String askUser() {
  String id = showInputDialog("Please enter user:");

  if (id == null)
    showMessageDialog(null, "You've canceled login operation!"
      , "Alert", ERROR_MESSAGE);

  else if ("".equals(id))
    showMessageDialog(null, "Empty user input!"
      , "Alert", ERROR_MESSAGE);

  else if (!accounts.hasKey(id = id.toLowerCase()))
    showMessageDialog(null, "Unknown \"" + id + "\" user!" + (id = "")
      , "Alert", ERROR_MESSAGE);

  return id;
}

boolean askPass(String id) {
  boolean isLogged = false;
  pwd.setText("");

  int action = showConfirmDialog(null, pwd
    , "Now enter password:", OK_CANCEL_OPTION);

  if (action != OK_OPTION) {
    showMessageDialog(null, "Password input canceled!"
      , "Alert", ERROR_MESSAGE);

    return false;
  }

  String phrase = pwd.getText();
  //String phrase = new String(pwd.getPassword());

  if ("".equals(phrase))
    showMessageDialog(null, "Empty password input!"
      , "Alert", ERROR_MESSAGE);

  else if (accounts.get(id).equals(phrase)) {
    showMessageDialog(null, "Welcome \"" + id + "\"!\nYou're logged in!"
      , "Info", INFORMATION_MESSAGE);

    isLogged = true;
    stage=2;
  } else
    showMessageDialog(null, "Password \"" + phrase + "\" mismatch!"
      , "Alert", ERROR_MESSAGE);

  return isLogged;
}

void confirmQuit() {
  if (showConfirmDialog(null, "Wanna quit then?", "Exit"
    , OK_CANCEL_OPTION) == OK_OPTION)  exit();
}

Using G4P GUI image buttons, how to use mouse pressed on the button, and make them go away after

$
0
0

I want my first page to have the image buttons i created with my gui, but then I want to create some sort of boolean/ mouse clicked when you click on them it'll change my programs page ( and the buttons will disapear). Is anyone familiar with this editor and can help me?

// Need G4P library
import g4p_controls.*;
int page=1;

int otisX, otisY= 200;
int maxX= 700;
int maxY= 200;

int W= 600, H= 600;

boolean OtisOver= false;
boolean MaxOver= false;

public void setup() {
  size(800, 600, JAVA2D);
  createGUI();
  customGUI();
}

public void draw() {
  page1();
  background(200);
  //pageSelector();
}


void pageSelector() {
  if (page==1) {
    page1();
  } else if (page==2) {
    page2();
  } else {
    page3();
  }
}
void page1() {
  background(#FF00FF);
  fill(250);
  rect(otisX, otisY, W, H);
  rect(maxX, maxY, W, H);
}
void page2() {
  background(#CE2121);
}
void page3() {
  background(#008000);
}
void mousePressed() {
  if (OtisOver (otisX, otisY, W, H)==true) {
    page2();
  }
  if (MaxOver (maxX, maxY, W, H)==true) {
    page3();
  }
}


boolean MaxOver(int x, int y, int w, int h) {
  if (mouseX >= x && mouseX <= x+w &&
    mouseY >= y && mouseY <= y+h) {
    return true;
  } else {
    return false;
  }
}

boolean OtisOver(int x, int y, int w, int h) {
  if (mouseX >= x && mouseX <= x+w &&
    mouseY >= y && mouseY <= y+h) {
    return true;
  } else {
    return false;
  }
}
public void customGUI() {
}

rundom numbers

$
0
0

Hello! i need help

As I can make random numbers? I put in the code: 0.0.0.0.0.0.0.0 I would like that every time you click the mouse do the numbers change their random manner.

For example: 10.40.57.05.02.09.45.66

the code:

void setup(){ // Initilaize the sketch size(600,400);

// VERY IMPORTANT: Allways initialize the library in the setup RG.init(this);

// Choice of colors background(0); fill(0,0,255); noStroke();

// Load the font file we want to use (the file must be in the data folder in the sketch floder), with the size 60 and the alignment CENTER grp = RG.getText("Bézier(0,0,0,0,0,0,0,0)", "FreeSans.ttf", 50, CENTER); }

void draw(){ // Clean frame background(0);

// Set the origin to draw in the middle of the sketch translate(width/2, height/2);

// Draw the string "Bézier" on the PGraphics canvas g (which is the default canvas of the sketch)
grp.draw(); }

How I can create a database using processing?

$
0
0

How I can create a database in which you can enter data of a person and they are stored in a database, you can also save some variables that person.

Error PGraphics 3D using Syphon

$
0
0

I'm using Syphon ibrary in processing 2.2.1 and i get always the same error :

"ClassCastException: processing.core.PGraphics3D cannot be cast to processing.opengl.PGraphicsOpenGL"

Any help please????

/* OpenProcessing Tweak of *@*http://www.openprocessing.org/sketch/6742*@* */
/* !do not delete the line above, required for linking your tweak if you upload again */

      ////////////////////////////
      //                        //
      //        doodle 3        //
      //                        //
      ////////////////////////////

      // (c) Martin Schneider 2009
      import codeanticode.syphon.*;
      PGraphics canvas;
    SyphonServer server;

    int n = 1000;
    int maxage = 20;
    int rdodge = 30;
    int opacity = 40;
    float speed = .2;
    float zoom = .01;
    boolean crayons, soft, dodge = true;

    float[][] a = new float[n][2];
    int[] age = new int[n];
    float w, h, s;
    int t, c;


    void setup() {
      size(500, 500,P3D);
      canvas = createGraphics(500, 500, P3D);
        // Create syhpon server to send frames out.
    server = new SyphonServer(this, "Processing Syphon");
      w = width/2;
      h = height/2;
      colorMode(HSB, TWO_PI, 2, 1);
      smooth();
      reset();

    }


    void draw() {
      canvas.beginDraw();
      // create new particles
      int np = n / maxage;
      for(int i=0; i<np & c<n; i++, c++) newp(c);
      // draw particle traces
      for(int i=0; i<c; i++) {
        age[i]++;
        float[] p = a[i];
        if (age[i] > maxage) newp(i);
        else {
          float[] f = f(p[0], p[1]);
          // opacity based on speed (soft mode) or age (hard mode)
          int m = maxage/2;
          float o = soft ? mag(f[0], f[1]) * 2 * opacity : (m - abs(m - age[i])) * opacity/m;
          // hue based on direction
          float h =  atan2(f[0], f[1]) + PI;
          canvas.stroke(h, crayons ? 1 : 0, crayons ? 1 : 0, o);
          // draw line while updating position
          canvas.line(p[0], p[1], p[0] += s*f[0],  p[1] += s*f[1]);
        }
      }
      canvas.endDraw();
      image(canvas, 0, 0);
      server.sendImage(canvas);
    }


    // noise based flow field
    float[] f(float x, float y) {;
      return new float[] {
        noise(t, x * zoom, y * zoom)-.5,
        noise(t+1, x * zoom, y * zoom) - .5
      };
    }


    void newp(int p) {
      if(dodge) {
        // particle inside a circle around the mouse position
        float r = random(rdodge), ang = random(TWO_PI);
        a[p] = new float[] { mouseX + r * cos(ang), mouseY + r *sin(ang) };
      } else {
        // particle anywhere on screen
        a[p] = new float[] { random(width), random(height) };
      }
      age[p] = 0;
    }


    void reset() {
      canvas.background(crayons ? 0 : #ffffff);
      s = speed / zoom;
      c = 0;
    }


    void keyPressed() {
      switch(key) {
        case 's' : soft = !soft; break;
        case 'd' : dodge = !dodge; break;
        case 'f' : t++; break;
        case 'c' : crayons = !crayons; break;
        case '+' : zoom /= 1.1; break;
        case '-' : zoom *= 1.1; break;
        case ' ' : break;
        default: return;
      }
      reset();
    }

Working with minim library - Fade in - Fade out ellipse ?

$
0
0

I just did this with the minim library by using amplitude of the sound .... my interest is to make a circle disappear , in the moment that you 'feed' with the sound it gets some colours re-appears again .... so my question is , is it possible to do that without background ... cause I have another sketch on top of this , so if I draw a background it doesn't involve the other sketch ...

I'll share the code with you ... but this is done with background

 import ddf.minim.*;
 import ddf.minim.analysis.*;
 import ddf.minim.effects.*;
 import ddf.minim.signals.*;
 import ddf.minim.spi.*;
 import ddf.minim.ugens.*;

 Minim minim;
 AudioInput in;

 // The data for the circles
 ArrayList<Float> cx = new ArrayList<Float>();
 ArrayList<Float> cy = new ArrayList<Float>();
 ArrayList<Float> cr = new ArrayList<Float>();

 int currCircle;
 float currAngle, prevAngle;
 int dir; // -1 or +1
 float speedFactor = 200;
 float speed;

 float prevTime, currTime;

 int ccCol, moverCol;

 // Data needed to manage connections
 ArrayList<Integer> from = new ArrayList<Integer>();
 ArrayList<Integer> to = new ArrayList<Integer>();
 ArrayList<Float> fromTouchAngle = new ArrayList<Float>();
 ArrayList<Float> toTouchAngle = new ArrayList<Float>();
 ArrayList<Boolean> reverse = new ArrayList<Boolean>();

 void setup() {
 size(600, 440);
 minim= new Minim(this);

 in = minim.getLineIn();

  // Initialise some colors for drawing
  ccCol = color(100, 230, 100);
 moverCol = color(255, 100, 100);
 // Create our circles
 addCircle(100, 100, 90);
 addCircle(300, 250, 160);
 addCircle(500, 250, 40);
 addCircle(300, 350, 60);
 addCircle(300, 320, 30);
 // Add connections
 addConnection(0, 1);
 addConnection(1, 2);
 addConnection(1, 3);
 addConnection(3, 4);
 // Starting position for mover
 currCircle = 1;
 speed = speedFactor / cr.get(currCircle);
 dir = 1;
 prevAngle = currAngle = random(TWO_PI);
 prevTime = currTime = millis();
  }

 void draw() {
 float currTime = millis();
 float elapsedTime = (currTime - prevTime) / 2500;
 background(0);
 drawCircles();
 updateMoverPosition(elapsedTime);
 drawMover();

 // Current tima and position become previous time
  // and position in the next frame
   prevTime = currTime;
   prevAngle = currAngle;
  }

   void updateMoverPosition(float et) {
    // Calculate current angle
    currAngle = prevAngle + dir * speed * et;
    if (currAngle < 0)
    currAngle += TWO_PI;
    else if (currAngle >= TWO_PI)
    currAngle -= TWO_PI;
   // Now see if the mover has reached a connection point
   float low = min(prevAngle, currAngle);
   float high = max(prevAngle, currAngle);
   // See if the previous and curent angles straddle the zero
   // degree position (that is east) we need to do this because
   // of the discontinuity in the angle value
   boolean straddleZero = (high - low > PI); // Straddle
  // Assume that we are not going to have to switch circles
   for (int i = 0; i < from.size(); i++) {
   // See if the connection is for the current circle
   if (from.get(i) == currCircle) {
   boolean switchCircle = false;
   float ta = fromTouchAngle.get(i);
   // See if the touch angle is between the previous and current
   // angle depending on whether the
   if (straddleZero) {
     switchCircle = ta > high || ta < low;
   } else {
    switchCircle = ta < high && ta > low;
    }
   if (switchCircle) {
    currCircle = to.get(i);
    prevAngle = currAngle = toTouchAngle.get(i);
    speed = speedFactor / cr.get(currCircle);
    if (reverse.get(i)) dir *= -1;
    break; // essential since we have changed circles
    }
    }
   }
   }

     void drawCircles() {
     stroke(0);
     float w = 0;
     for(int i=0;i<150; i++ ){
     w += in.mix.get(i);
    }
    strokeWeight(abs(w));
    noFill();
    for (int i = 0; i < cx.size(); i++) {
    float d = cr.get(i) * 2;
    ellipse(cx.get(i), cy.get(i), d, d);
    }
    }

   void drawMover() {
   noStroke();
  //fill(255);
    float w = 0;
   for(int i=0;i<10; i++ ){
   w += in.mix.get(i);
    }
    fill(255*abs(w));

   float x = cx.get(currCircle);
   float y = cy.get(currCircle);
   float r = cr.get(currCircle);
  x += r * cos(currAngle);
  y += r * sin(currAngle);
  ellipse(x, y, 14, 14);
  }

   void addCircle(float x, float y, float r) {
   cx.add(x);
   cy.add(y);
   cr.add(r);
    }

   void addConnection(int fromCirc, int toCirc) {
   float fX = cx.get(fromCirc);
   float fY = cy.get(fromCirc);
   float fR = cr.get(fromCirc);
   float tX = cx.get(toCirc);
   float tY = cy.get(toCirc);
   // Angle from-circle-centre >> to-circle-centre
   float ang = atan2(tY - fY, tX - fX);
   // Calculate where the 2 circles touch
   float touchX = fX + fR * cos(ang);
   float touchY = fY + fR * sin(ang);
   // Calculate touch angle for both circles and
   // make sure they fall in the range 0 - TWO_PI
   float fAngle = atan2(touchY - fY, touchX - fX);
   if (fAngle < 0) fAngle += TWO_PI;
   float tAngle = atan2(touchY - tY, touchX - tX);
   if (tAngle < 0) tAngle += TWO_PI;
   // Determine whther we need to reverse direction when
   // we change circle
   boolean reverseDir = abs(fAngle - tAngle) > 0.9;
   // Add forward connection
   from.add(fromCirc);
   to.add(toCirc);
   fromTouchAngle.add(fAngle);
   toTouchAngle.add(tAngle);
   reverse.add(reverseDir);
   // Add reverse connection
   from.add(toCirc);
   to.add(fromCirc);
   fromTouchAngle.add(tAngle);
    toTouchAngle.add(fAngle);
   reverse.add(reverseDir);
     }

In below code error Array out of bounds is coming in portName= Serial.list()[PortSelected];this line

$
0
0

import processing.serial.*; int SerialPortNumber=2; int PortSelected=2;

/* =================================================================================
Global variables =================================================================================*/

int xValue, yValue, Command; boolean Error=true;

boolean UpdateGraph=true; int lineGraph; int ErrorCounter=0; int TotalRecieved=0;

/* =================================================================================
Local variables =================================================================================*/ boolean DataRecieved1=false, DataRecieved2=false, DataRecieved3=false;

float[] DynamicArrayTime1, DynamicArrayTime2, DynamicArrayTime3; float[] Time1, Time2, Time3; float[] Voltage1, Voltage2, Voltage3; float[] current; float[] DynamicArray1, DynamicArray2, DynamicArray3;

float[] PowerArray= new float[0]; // Dynamic arrays that will use the append() float[] DynamicArrayPower = new float[0]; // function to add values float[] DynamicArrayTime= new float[0];

String portName; String[] ArrayOfPorts=new String[SerialPortNumber];

boolean DataRecieved=false, Data1Recieved=false, Data2Recieved=false; int incrament=0;

int NumOfSerialBytes=8; // The size of the buffer array int[] serialInArray = new int[NumOfSerialBytes]; // Buffer array int serialCount = 0; // A count of how many bytes received int xMSB, xLSB, yMSB, yLSB; // Bytes of data

Serial myPort; // The serial port object

/* =================================================================================
A once off serail port setup function. In this case the selection of the speed, the serial port and clearing the serial port buffer
=================================================================================*/

void SerialPortSetup() {

// text(Serial.list().length,200,200);

portName= Serial.list()[PortSelected]; // println( Serial.list()); ArrayOfPorts=Serial.list(); println(ArrayOfPorts); myPort = new Serial(this, portName, 115200); delay(50); myPort.clear(); myPort.buffer(20); }

/* ============================================================
serialEvent will be called when something is sent to the serial port being used. ============================================================ */

void serialEvent(Serial myPort) {

while (myPort.available ()>0) { /* ============================================================
Read the next byte that's waiting in the buffer. ============================================================ */

int inByte = myPort.read();

if (inByte==0)serialCount=0;

if (inByte>255) {
  println(" inByte = "+inByte);
  exit();
}

// Add the latest byte from the serial port to array:

serialInArray[serialCount] = inByte;
serialCount++;

Error=true;
if (serialCount >= NumOfSerialBytes ) {
  serialCount = 0;

  TotalRecieved++;

  int Checksum=0;

  //    Checksum = (Command + yMSB + yLSB + xMSB + xLSB + zeroByte)%255;
  for (int x=0; x<serialInArray.length-1; x++) {
    Checksum=Checksum+serialInArray[x];
  }

  Checksum=Checksum%255;



  if (Checksum==serialInArray[serialInArray.length-1]) {
    Error = false;
    DataRecieved=true;
  }
  else {
    Error = true;
    //  println("Error:  "+ ErrorCounter +" / "+ TotalRecieved+" : "+float(ErrorCounter/TotalRecieved)*100+"%");
    DataRecieved=false;
    ErrorCounter++;
    println("Error:  "+ ErrorCounter +" / "+ TotalRecieved+" : "+float(ErrorCounter/TotalRecieved)*100+"%");
  }
}

if (!Error) {


  int zeroByte = serialInArray[6];
  // println (zeroByte & 2);

  xLSB = serialInArray[3];
  if ( (zeroByte & 1) == 1) xLSB=0;
  xMSB = serialInArray[2];
  if ( (zeroByte & 2) == 2) xMSB=0;

  yLSB = serialInArray[5];
  if ( (zeroByte & 4) == 4) yLSB=0;

  yMSB = serialInArray[4];
  if ( (zeroByte & 8) == 8) yMSB=0;


  //   println( "0\tCommand\tyMSB\tyLSB\txMSB\txLSB\tzeroByte\tsChecksum");
  //  println(serialInArray[0]+"\t"+Command +"\t"+ yMSB +"\t"+ yLSB +"\t"+ xMSB +"\t"+ xLSB+"\t" +zeroByte+"\t"+ serialInArray[7]);

  // >=====< combine bytes to form large integers >==================< //

  Command  = serialInArray[1];

  xValue   = xMSB << 8 | xLSB;                    // Get xValue from yMSB & yLSB
  yValue   = yMSB << 8 | yLSB;                    // Get yValue from xMSB & xLSB

    // println(Command+ "  "+xValue+"  "+ yValue+" " );

  /*

How that works: if xMSB = 10001001 and xLSB = 0100 0011 xMSB << 8 = 10001001 00000000 (shift xMSB left by 8 bits)
xLSB = 01000011
xLSB | xMSB = 10001001 01000011 combine the 2 bytes using the logic or | xValue = 10001001 01000011 now xValue is a 2 byte number 0 -> 65536
*/

  /*  ==================================================================
   Command, xValue & yValue have now been recieved from the chip
   ==================================================================  */

  switch(Command) {


    /*  ==================================================================
     Recieve array1 and array2 from chip, update oscilloscope
     ==================================================================  */

  case 1: // Data is added to dynamic arrays
    DynamicArrayTime3=append( DynamicArrayTime3, (xValue) );
    DynamicArray3=append( DynamicArray3, (yValue) );

    break;

  case 2: // An array of unknown size is about to be recieved, empty storage arrays
    DynamicArrayTime3= new float[0];
    DynamicArray3= new float[0];
    break;

  case 3:  // Array has finnished being recieved, update arrays being drawn
    Time3=DynamicArrayTime3;
    Voltage3=DynamicArray3;
 //   println(Voltage3.length);
    DataRecieved3=true;
    break;

    /*  ==================================================================
     Recieve array2 and array3 from chip
     ==================================================================  */


  case 4: // Data is added to dynamic arrays
    DynamicArrayTime2=append( DynamicArrayTime2, xValue );
    DynamicArray2=append( DynamicArray2, (yValue-16000.0)/32000.0*20.0  );
    break;

  case 5: // An array of unknown size is about to be recieved, empty storage arrays
    DynamicArrayTime2= new float[0];
    DynamicArray2= new float[0];
    break;

  case 6:  // Array has finnished being recieved, update arrays being drawn
    Time2=DynamicArrayTime2;
    current=DynamicArray2;
    DataRecieved2=true;
    break;

    /*  ==================================================================
     Recieve a value of calculated power consumption & add it to the
     PowerArray.
     ==================================================================  */
  case 20:
    PowerArray=append( PowerArray, yValue );

    break;

  case 21:
    DynamicArrayTime=append( DynamicArrayTime, xValue );
    DynamicArrayPower=append( DynamicArrayPower, yValue );



    break;
  }
}

} redraw();
// } }


Importing libraries in .java tabs

$
0
0

Hi guys, I'm kind of new with Processing 3.* and surely new in this community. I am (and willing to) using the Processing Development Environment (The official IDE). Reading the official "guide", in particular this part: https://processing.org/reference/environment/#Tabs, it is specified that you can use pure Java language inside Processing simply naming a .java tab instead of a .pde one.

This kind of solution is good for example to use enums (otherwise not usable in .pde tabs) and there are other reasons, but they are not important at the moment...

A problem with this kind of work is that the libraries of Processing are not included, so you have to import them manually.

What I "found" is that all the official Processing libraries can be imported simply with the import keyword, while for all the libraries installed by the Contribution Manager the story is different. The error message is The package "packageName" does not exists. You might be missing a library. Libraries must be installed in a folder named 'libraries' inside the 'sketchbook' folder.

Long story short I can't import those libraries...

I tried to copy them in the standard java libraries location (%SystemRoot%\Java\lib\ext) and in some other paths, but nothing... I read that using classpath would allow as to use it but I can't understand how to use Processing with javac.

I tried something like "ProcessingFolder\processing-java.exe" --sketch="$(CURRENT_DIRECTORY)" --run that is the same script you can use to run Processing in Notepad++, adding the statement --classpath="$(CURRENT_DIRECTORY)" but it didn't work (processing-java.exe state I don't know anything about --classpath=.).

So here's the question: How can we import and use libraries in .java tabs using Processing Development Environment?

Processing and ODBC Connection to Database?

$
0
0

Hi, is there some solution or way to connect processing with Postgresql for example? How to realize the minimum distance between Processing and DB? Any ideas?

Reading a color value from webcam.

$
0
0

Hello, I am making a small program that reads what color hat you are wearing and then performs a virtual key press via a robot to interact with a game. I got it sort of working so far in that it will detect red colors but not blue or green. I am using a hue color index to track the colors. Any idea of how I could do it differently or if there is anything I am missing.

// check for red pixels int redPixelCount = 0; int bluePixelCount = 0; int greenPixelCount = 0; int yellowPixelCount= 0; for (int x=0; x<640; x++) { for (int y=0; y<240; y++) { color c = get(x, y); int px = cam.pixels[y*width+x]; float h = hue(px); float s = saturation(px); float b = brightness(px); // if it's bright, saturated and a specific color if (b > 100 && s > 100 && (h < 20 || h > 230)) { redPixelCount++; } if (b > 100 && s > 100 && (h < 240 && h > 180)) { bluePixelCount++; } if (b > 100 && s > 100 && (h < 80 && h > 140)) { greenPixelCount++; } if (b > 100 && s > 100 && (h < 50 && h > 70)) { yellowPixelCount++; } } }

Controlling child window properties.

$
0
0

In the example: Demos > Tests > MultipleWindows
I would like to create a child window which does not close the main window when closed. The purpose is to have an inspection window which will be created for a short time, then closed, and then something else is inspected. My hunch is that it's something with JFrame if I'm not confused, but I probably am because I can't find anything.

After using the G4P library, I've noticed that after about three to seven windows are created and closed in procession, my entire computer starts going very slowly, but my resource monitor shows nothing specific. So, I'm looking to build the windows from scratch to see if it's any different or if it's my computer.

Error from video library in Ubuntu 16.04

$
0
0

Hi there

I'm getting an error when trying to use the video library using Capture in Linux Ubuntu 16.04 in a 64 bits machine. Actually I tried in two different machines with fresh installs and got the same results. I have searched a lot in the internet for a solution and could not find it.

The error says to "'Run Sketches on Display' preference to display 1" but in the preferences I have this like so: run.display=1 which I think is what it is mentioning.

Setting 'Run Sketches on Display' preference to display 1 UnsatisfiedLinkError: Error looking up function 'gst_date_get_type': /usr/lib/x86_64-linux-gnu/libgstreamer-1.0.so.0.800.0: undefined symbol: gst_date_get_type A library relies on native code that's not available. Or only works properly when the sketch is run as a 32-bit application.

I'm really out of ideas. Someone out there know what I have to do or have a direction to point me? It will be much appreciated.

best regards, Gil

Issue installing processing-sound library

$
0
0

I am new to Processing and I have some issues installing the processing-sound library. I installed the oscP5 libary here and it works fine: C:\Users\51syvjan\Documents\Processing\libraries\oscP5

However when downloading processing-sound-master zip from here: _https://github.com/processing/processing-sound and extracting it to: C:\Users\51syvjan\Documents\Processing\libraries\processing-sound it is not picked up by Processing. Any suggestions on what the issue can be?

jsonObject is ambiguous

$
0
0

Now the code below is a mixture of two sketches. The goal here is that the user inputs a search term. Upon hitting enter the applet searches tinysong for the song and returns the song id (this works in its own sketch). The term is simultaneously searched for on twitter using the twitter4j library(this also works on its own.)

However when I put the two together i get the following error "jsonObject is ambiguous" ???????

for the purpose of this example I removed my api keys..

Any help would be awesome.

import controlP5.*;
//import java.net.*;
/////////////////////
ControlP5 controlP5;
controlP5.Label label;
Textfield myTextfield; /// setting up text-input field
int myBitFontIndex;
PFont p = createFont("Avenir",32);
///////////////////




/* TinySong API*/ // this is how you search the grooveshark database.

String tinyK = "";

int songIdNum;

String searchT; // the user inputs their query
String searchString;

ConfigurationBuilder cb = new ConfigurationBuilder();
Twitter twitterInstance;
Query queryForTwitter;


ArrayList tweets;
String[] userName = new String[0];
String[] tweetsArr = new String[0];


void setup(){

  size(1024,640);

  ////////////////////
  cb.setOAuthConsumerKey("");
  cb.setOAuthConsumerSecret("");
  cb.setOAuthAccessToken("");
  cb.setOAuthAccessTokenSecret("");

  twitterInstance = new TwitterFactory( cb.build() ).getInstance();

  ///////////////////
  int txtFw = 440;

  controlP5 = new ControlP5(this);
  controlP5.setControlFont(p);

  myTextfield = controlP5.addTextfield("enter a song name",(width/2)-(txtFw/2),(height/11)*2,txtFw,80);
  myTextfield.setFocus(true);
  //myTextfield.valueLabel().setFont(myBitFontIndex);
  myTextfield.valueLabel().style().marginTop = -6;

  ////////////////////////////////////

}

void draw(){

  background(0);
  finTweets();
}



void keyPressed(){

  if(key == ENTER || key == RETURN){

      searchT = myTextfield.getText();
      searchT = searchT.replaceAll(" ","+");

      FetchTweets();

      println(searchT);
      searchString = "http://tinysong.com/b/"+searchT+"?format=json&key="+tinyK;

  ///////////////////


  ///////////////////
  println(searchString);
    try{
        String url = searchString;

        JSONObject wholeJson = new JSONObject(join(loadStrings(url),""));
        JSONObject resp = wholeJson; // remove .getJSONObject(""); as this json file has no objects
        songIdNum = resp.getInt("SongID");
//        songIdNum = resp.getInt("m");

        println("The song ID for "+searchT+" is: "+songIdNum);

    }
    catch(JSONException e){
      println("there was an error parsing the JSONObject");
    }
  }

}

void FetchTweets(){

  String twitQ = "#"+searchT;
  queryForTwitter = new Query(twitQ);

  try{

    QueryResult result = twitterInstance.search(queryForTwitter);
    tweets = (ArrayList) result.getTweets();
    }
    catch (TwitterException te){
      println("couldn't connect this time" + te);
    }//end catch
}//end function


void finTweets(){

  for(int i=0; i<tweets.size(); i++){
      Status t = (Status) tweets.get(i);

      userName = append(userName, t.getUser().getScreenName());
      tweetsArr = append(tweetsArr, t.getText());// adds tweets to array
      //get geoLoc later
      text(userName[i] + "said: " + tweetsArr[i],20,15+i*30,width-20,40);

    }//end loop
}

gicentre Zoom Pan

$
0
0

I'd like to know how to change the zoomer ZoomPan setting in GICentre library. I've tried the following:

zoomer.setZoomPanDirection(ZOOM_HORIZONTAL_PAN_BOTH);

but I get a syntax error as it interprets ZOOM_HORIZONTAL_PAN_BOTH as a variable whereas as it should be an Enum. I'm not so familiar with Enum's, but I found the documentation here:

gicentre.org/utils/reference/org/gicentre/utils/move/ZoomPan.ZoomPanDirection.html

I think I just need to know the correct syntax.

Here's an example program:

    import org.gicentre.utils.move.*;

    ZoomPan zoomer;

    void setup(){
      size(600,300);
      zoomer = new ZoomPan(this);
    }

    void draw(){
      background(255);
      zoomer.transform();
      zoomer.setZoomPanDirection(ZOOM_HORIZONTAL_PAN_BOTH);
      stroke(50);

      line(100,height/2,500,height/2);

      ellipse(100,100, 50, 50);
    }

Many thanks.

How to export to svg using library processing.svg.*;)

$
0
0

Hi there, Can anyone please let me know if there is a reference for the library processing.svg? Thanks Paul

How to read a https webpage?

$
0
0

I've been trying the http requests library but it doesn't seem to handle https requests.

The context is that I want to read and send (i.e. get and post) to an IoT device. It seems to have only https communications available.

Create TAP TEMPO / METRONOME

$
0
0

Hello.

I have a few months of experience with Processing, but I guess that this is an algorithm related question.

So, I have a processing project that plays sounds when the user press some PAD on MIDI or even KEYBOARD and I want to try to play a beap continuously according to BPM.

What I have tried:

import processing.sound.*; SoundFile beap; int bpm = 95; int secs = 1; void setup() { frameRate(60); fullScreen(); beap = new SoundFile(this, "sounds/bip.mp3"); } void draw(){ secs++; beap.play(); }

But, this of course plays beap continuously. Anybody can help me?

NOTE: changing frameRate(); does not help because it'll mess with rendering graphics.

Thanks

Not sure how to go about it. (play video on key press)

$
0
0

Hi,

I'm trying to figure out how I would go about creating a code that will trigger a video when I hit a certain key on the keyboard. the key doesn't have to be specific, I have found various other example codes that trigger other things when you hit a key but not ones that integrate a video. Any help would be greatly appreciated! Thank you.

Viewing all 2896 articles
Browse latest View live