//-------------------------------------------------------------------------------- ofRectangle ofxCvImage::getROI() const { CvRect rect = cvGetImageROI(cvImage); return ofRectangle((float)rect.x, (float)rect.y, (float)rect.width, (float)rect.height); }
//-------------------------------------------------------------- void testApp::setup(){ ofBackground(255,255,255); ofTrueTypeFont legendFont; legendFont.loadFont("verdana.ttf", 12, true, true); // pins // timeWindow // yScale // yOffset // colors // names // Setup Arduino string arduinoPort = "\\\\.\\COM10"; arduino.connect(arduinoPort, 57600); while(!arduino.isArduinoReady()); arduino.sendAnalogPinReporting(0, ARD_ANALOG); arduino.sendAnalogPinReporting(1, ARD_ANALOG); arduino.sendAnalogPinReporting(2, ARD_ANALOG); arduino.sendAnalogPinReporting(3, ARD_ANALOG); arduino.sendAnalogPinReporting(4, ARD_ANALOG); arduino.update(); // Log Directory logDirPath = "../LogData/"; logger.setDirPath(logDirPath); nScopes = 2; ofRectangle scopeArea = ofRectangle(ofPoint(0,0), ofGetWindowSize()); scopeWin = ofxMultiScope(nScopes, scopeArea, legendFont); // Setup the multiScope panel samplingFreq = 50.; // Sampling rate (Hz) { // Scope 1 setup const int nVariables = 3; nPlotsScope0 = nVariables; float timeWindow = 5.; // seconds float yScale = 0.5; // yScale multiplier float yOffset = -256.; // yOffset from the center of the scope window ofColor colors[nVariables] = {ofColor(255,0,0), ofColor(0,255,0), ofColor(0,0,255)}; std::vector<ofColor> vec_colors(colors, colors + nVariables); string names[nVariables] = {"A0", "A1", "A2"}; std::vector<string> vec_names(names, names + nVariables); scopeWin.scopes.at(0).setup(timeWindow, samplingFreq, vec_names, vec_colors, yScale, yOffset); // Setup each oscilloscope panel } { // Scope 2 setup const int nVariables = 2; nPlotsScope1 = nVariables; float timeWindow = 10.; // seconds float yScale = 0.5; // yScale multiplier float yOffset = -256.; // yOffset from the center of the scope window ofColor colors[nVariables] = {ofColor(0,0,0), ofColor(255,0,255)}; std::vector<ofColor> vec_colors(colors, colors + nVariables); string names[nVariables] = {"A3", "A4"}; std::vector<string> vec_names(names, names + nVariables); scopeWin.scopes.at(1).setup(timeWindow, samplingFreq, vec_names, vec_colors, yScale, yOffset); // Setup each oscilloscope panel } selectedScope = 0; // Select all scopes for increment/decrement isPaused = false; isRecording = false; loopTimer = (unsigned long) ofGetElapsedTimeMillis(); logger.startThread(); }
/***************************************************************************** * KEY EVENTS *****************************************************************************/ void ofxNCoreVision::_keyPressed(ofKeyEventArgs &e) { if (showConfiguration) { switch (e.key) { case 'b': if(!bFidMode) { filter->bLearnBakground = true; } else { filter_fiducial->bLearnBackground = true; } break; case 'o': bDrawOutlines ? bDrawOutlines = false : bDrawOutlines = true; controls->update(appPtr->trackedPanel_outlines, kofxGui_Set_Bool, &appPtr->bDrawOutlines, sizeof(bool)); break; case 'h': filter->bHorizontalMirror ? filter->bHorizontalMirror = false : filter->bHorizontalMirror = true; filter_fiducial->bHorizontalMirror ? filter_fiducial->bHorizontalMirror = false : filter_fiducial->bHorizontalMirror = true; controls->update(appPtr->propertiesPanel_flipH, kofxGui_Set_Bool, &appPtr->filter->bHorizontalMirror, sizeof(bool)); break; case 'j': filter->bVerticalMirror ? filter->bVerticalMirror = false : filter->bVerticalMirror = true; filter_fiducial->bVerticalMirror ? filter_fiducial->bVerticalMirror = false : filter_fiducial->bVerticalMirror = true; controls->update(appPtr->propertiesPanel_flipV, kofxGui_Set_Bool, &appPtr->filter->bVerticalMirror, sizeof(bool)); break; case 't': myTUIO.bOSCMode = !myTUIO.bOSCMode; myTUIO.bTCPMode = false; myTUIO.bBinaryMode = false; bTUIOMode = myTUIO.bOSCMode; controls->update(appPtr->optionPanel_tuio_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bTCPMode, sizeof(bool)); controls->update(appPtr->optionPanel_tuio_osc, kofxGui_Set_Bool, &appPtr->myTUIO.bOSCMode, sizeof(bool)); controls->update(appPtr->optionPanel_bin_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bBinaryMode, sizeof(bool)); //clear blobs // myTUIO.blobs.clear(); break; case 'f': myTUIO.bOSCMode = false; myTUIO.bTCPMode = !myTUIO.bTCPMode; myTUIO.bBinaryMode = false; bTUIOMode = myTUIO.bTCPMode; controls->update(appPtr->optionPanel_tuio_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bTCPMode, sizeof(bool)); controls->update(appPtr->optionPanel_tuio_osc, kofxGui_Set_Bool, &appPtr->myTUIO.bOSCMode, sizeof(bool)); controls->update(appPtr->optionPanel_bin_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bBinaryMode, sizeof(bool)); //clear blobs // myTUIO.blobs.clear(); break; case 'n': myTUIO.bOSCMode = false; myTUIO.bTCPMode = false; myTUIO.bBinaryMode = !myTUIO.bBinaryMode; bTUIOMode = myTUIO.bBinaryMode; controls->update(appPtr->optionPanel_tuio_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bTCPMode, sizeof(bool)); controls->update(appPtr->optionPanel_tuio_osc, kofxGui_Set_Bool, &appPtr->myTUIO.bOSCMode, sizeof(bool)); controls->update(appPtr->optionPanel_bin_tcp, kofxGui_Set_Bool, &appPtr->myTUIO.bBinaryMode, sizeof(bool)); //clear blobs // myTUIO.blobs.clear(); break; case 'g': // bGPUMode ? bGPUMode = false : bGPUMode = true; // filter->bLearnBakground = true; break; case 'v': if (bcamera && vidGrabber != NULL) #ifdef TARGET_WIN32 if(PS3) PS3->showSettings(); else if(vidGrabber) vidGrabber->videoSettings(); #else vidGrabber->videoSettings(); #endif break; case 'l': bShowLabels ? bShowLabels = false : bShowLabels = true; controls->update(appPtr->trackedPanel_ids, kofxGui_Set_Bool, &appPtr->bShowLabels, sizeof(bool)); break; case 'p': bShowPressure ? bShowPressure = false : bShowPressure = true; break; case ' ': if (bMiniMode && !bCalibration) // NEED TO ADD HERE ONLY GO MINI MODE IF NOT CALIBRATING { bMiniMode = false; bShowInterface = true; filter->bMiniMode = bMiniMode; filter_fiducial->bMiniMode = bMiniMode; ofSetWindowShape(950,600); //default size } else if(!bCalibration) { bMiniMode = true; bShowInterface = false; filter->bMiniMode = bMiniMode; filter_fiducial->bMiniMode = bMiniMode; ofSetWindowShape(190,200); //minimized size } break; case 'x': //Exit Calibrating if (bCalibration) { bShowInterface = true; bCalibration = false; calib.calibrating = false; tracker.isCalibrating = false; if (bFullscreen == true) ofToggleFullscreen(); bFullscreen = false; } break; case OF_KEY_RETURN: //Close Template Selection and save it if( contourFinder.bTrackObjects && isSelecting ) { isSelecting = false; templates.addTemplate(rect,minRect,maxRect,camWidth/320,camHeight/240); rect = ofRectangle(); minRect = rect; maxRect = rect; minTempArea = 0; maxTempArea = 0; controls->update(appPtr->TemplatePanel_minArea, kofxGui_Set_Float, &appPtr->minTempArea, sizeof(float)); controls->update(appPtr->TemplatePanel_maxArea, kofxGui_Set_Float, &appPtr->maxTempArea, sizeof(float)); } break; case 'i': bFidMode = !bFidMode; if(bFidMode) {//Update the GUI with Fiducial Filter values //Smooth controls->update(appPtr->smoothPanel_use, kofxGui_Set_Bool, &appPtr->filter_fiducial->bSmooth, sizeof(bool)); controls->update(appPtr->smoothPanel_smooth, kofxGui_Set_Float, &appPtr->filter_fiducial->smooth, sizeof(float)); //Highpass controls->update(appPtr->highpassPanel_use, kofxGui_Set_Bool, &appPtr->filter_fiducial->bHighpass, sizeof(bool)); controls->update(appPtr->highpassPanel_blur, kofxGui_Set_Float, &appPtr->filter_fiducial->highpassBlur, sizeof(float)); controls->update(appPtr->highpassPanel_noise, kofxGui_Set_Float, &appPtr->filter_fiducial->highpassNoise, sizeof(float)); //Amplify controls->update(appPtr->amplifyPanel_use, kofxGui_Set_Bool, &appPtr->filter_fiducial->bAmplify, sizeof(bool)); controls->update(appPtr->amplifyPanel_amp, kofxGui_Set_Float, &appPtr->filter_fiducial->highpassAmp, sizeof(float)); //Threshold controls->update(appPtr->trackedPanel_threshold, kofxGui_Set_Float, &appPtr->filter_fiducial->threshold, sizeof(float)); } else {//Update the GUI with normal Filter values //Smooth controls->update(appPtr->smoothPanel_use, kofxGui_Set_Bool, &appPtr->filter->bSmooth, sizeof(bool)); controls->update(appPtr->smoothPanel_smooth, kofxGui_Set_Float, &appPtr->filter->smooth, sizeof(float)); //Highpass controls->update(appPtr->highpassPanel_use, kofxGui_Set_Bool, &appPtr->filter->bHighpass, sizeof(bool)); controls->update(appPtr->highpassPanel_blur, kofxGui_Set_Float, &appPtr->filter->highpassBlur, sizeof(float)); controls->update(appPtr->highpassPanel_noise, kofxGui_Set_Float, &appPtr->filter->highpassNoise, sizeof(float)); //Amplify controls->update(appPtr->amplifyPanel_use, kofxGui_Set_Bool, &appPtr->filter->bAmplify, sizeof(bool)); controls->update(appPtr->amplifyPanel_amp, kofxGui_Set_Float, &appPtr->filter->highpassAmp, sizeof(float)); //Threshold controls->update(appPtr->trackedPanel_threshold, kofxGui_Set_Float, &appPtr->filter->threshold, sizeof(float)); } //TODO:Update the GUI break; default: //Check key character <<<<===== Remove this //printf("%c",e.key); break; } } }
void form::draw() { for (int i=0; i<mParticles.size();i++) { mMesh.setVertex(i, mParticles[i]->getPosition()); mOuterMesh.setVertex(i, mBottomParticles[i]->getPosition()); } glEnable( GL_DEPTH_TEST ); mCamera.begin(ofRectangle(ofGetHeight(), 0, ofGetHeight(), ofGetHeight())); ofSetColor(255,0,128); ofEnableLighting(); ofSetColor(255, 255, 255); mLight.enable(); mLight.setPosition(ofVec3f(30, -15+5, -1)); mLight.setAttenuation(0.75,0,0); ofSetColor(185, 185, 185); for(int i=0; i<mBounds.size();i++) { mBounds[i]->draw(); } ofDisableAlphaBlending(); ofDisableBlendMode(); ofSetColor(255, 0, 128); ofMaterial meshmat; meshmat.setColors(ofColor(255,0,128), ofColor(255,0,128), ofColor(100,0,60), ofColor(0,0,0)); meshmat.setShininess(0.5); meshmat.begin(); mMesh.ofMesh::draw(OF_MESH_FILL); mOuterMesh.ofMesh::draw(OF_MESH_FILL); for (int i=1; i<mMasterEdgeParticles.size();i++) { ofBeginShape(); ofVertex((ofPoint &)mBottomParticles[mMasterEdgeParticles[i-1]->array_ind]->getPosition()); ofVertex((ofPoint &)mBottomParticles[mMasterEdgeParticles[i]->array_ind]->getPosition()); ofVertex((ofPoint &)mParticles[mMasterEdgeParticles[i]->array_ind]->getPosition()); ofVertex((ofPoint &)mParticles[mMasterEdgeParticles[i-1]->array_ind]->getPosition()); ofEndShape(); } for (int i=1; i<mSlaveEdgeParticles.size();i++) { ofBeginShape(); ofVertex((ofPoint &)mBottomParticles[mSlaveEdgeParticles[i-1]->array_ind]->getPosition()); ofVertex((ofPoint &)mBottomParticles[mSlaveEdgeParticles[i]->array_ind]->getPosition()); ofVertex((ofPoint &)mParticles[mSlaveEdgeParticles[i]->array_ind]->getPosition()); ofVertex((ofPoint &)mParticles[mSlaveEdgeParticles[i-1]->array_ind]->getPosition()); ofEndShape(); } meshmat.end(); mLight.disable(); ofDisableLighting(); if (mMasterEdgeParticles.size()>0) { part_and_index *pai = mMasterEdgeParticles[0]; //for (auto pai : mMasterEdgeParticles) { ofPushMatrix(); ofTranslate(pai->part->getPosition()); ofSpherePrimitive(3, 5).draw(); ofPopMatrix(); //} pai = mSlaveEdgeParticles[0]; //for (auto pai : mSlaveEdgeParticles) { ofPushMatrix(); ofTranslate(pai->part->getPosition()); ofSpherePrimitive(3, 5).draw(); ofPopMatrix(); //} } ofSetColor(255,255,255); for (int i=0; i<mAtZip;i++) { if (i < mZipperSprings.size()) { ofLine(mZipperSprings[i]->getOneEnd()->getPosition(),mZipperSprings[i]->getTheOtherEnd()->getPosition()); } } /*ofSetColor(255,0,255); for (int i=0; i<mMiddleSprings.size();i++) { ofLine(mMiddleSprings[i]->getOneEnd()->getPosition(),mMiddleSprings[i]->getTheOtherEnd()->getPosition()); }*/ mCamera.end(); glDisable(GL_DEPTH_TEST); }
void ofxTLSwitches::draw(){ ofPushStyle(); ofFill(); //draw a little wobble if its on //if(isOnAtMillis(timeline->getCurrentTimeMillis())){ //play solo change if(isOn()){ ofSetColor(timeline->getColors().disabledColor, 20+(1-powf(sin(ofGetElapsedTimef()*5)*.5+.5,2))*20); ofRect(bounds); } for(int i = 0; i < keyframes.size(); i++){ ofxTLSwitch* switchKey = (ofxTLSwitch*)keyframes[i]; float startScreenX = millisToScreenX(switchKey->timeRange.min); float endScreenX = millisToScreenX(switchKey->timeRange.max); switchKey->display = ofRectangle(startScreenX, bounds.y, endScreenX-startScreenX, bounds.height); //draw handles ofSetLineWidth(2); bool keyIsSelected = isKeyframeSelected(switchKey); if(keyIsSelected || switchKey->startSelected){ ofSetColor(timeline->getColors().textColor); } else{ ofSetColor(timeline->getColors().keyColor); } ofLine(switchKey->display.x, bounds.y, switchKey->display.x, bounds.y+bounds.height); if(keyIsSelected || switchKey->endSelected){ ofSetColor(timeline->getColors().textColor); } else{ ofSetColor(timeline->getColors().keyColor); } ofLine(switchKey->display.x+switchKey->display.width, bounds.y, switchKey->display.x+switchKey->display.width, bounds.y+bounds.height); //draw region if(keyIsSelected){ ofSetColor(timeline->getColors().textColor, 100); } else{ ofSetColor(timeline->getColors().keyColor, 100); } //set overlay colors, this will override the colors above if(hoverKeyframe == switchKey){ if(startHover){ ofPushStyle(); if(switchKey->startSelected){ ofSetColor(timeline->getColors().highlightColor); } else{ ofSetColor(timeline->getColors().keyColor); } ofRect(switchKey->display.x-2, bounds.y, 4, bounds.height); ofPopStyle(); } else if(endHover){ ofPushStyle(); if(switchKey->endSelected){ ofSetColor(timeline->getColors().highlightColor); } else{ ofSetColor(timeline->getColors().keyColor); } ofRect(switchKey->display.x+switchKey->display.width-2, bounds.y, 4.0, bounds.height); ofPopStyle(); } else { if(keyIsSelected){ ofSetColor(timeline->getColors().highlightColor); }else { ofSetColor(timeline->getColors().keyColor); } } } ofRect(switchKey->display); } ofPopStyle(); }
//-------------------------------------------------- ofRectangle ofGetWindowRect() { return ofRectangle(0, 0, ofGetWindowWidth(), ofGetWindowHeight()); }
void GameSprite::setCurrentFrame(int frame){ if (frame < currentAnimation.numFrames && currentFrame != lastFrame){ currentImageData = &(spriteMan->spriteData[spriteDataIndex]); int width = currentImageData->dimensions.x; int height = currentImageData->dimensions.y; unsigned char * newPix = new unsigned char [ width * height * 4]; unsigned char * pix = currentImageData->image.getPixels(); int srcX = frame * width; int srcY = currentAnimation.spriteRow * height; int ct = 0; //temps for working out the frames bounding box int firstY = 10000; int firstX = -1; int lastY = -1; int lastX = -1; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ int subPos = 0; if(mirror){ subPos = ((width - x) + y * width) * 4; } else { subPos = (x + y * width) * 4; } int mainPos = ((srcX + x) + (srcY + y) * currentImageData->image.width) * 4; newPix[subPos] = pix[mainPos]; newPix[subPos + 1] = pix[mainPos + 1]; newPix[subPos + 2] = pix[mainPos + 2]; newPix[subPos + 3] = pix[mainPos + 3]; if(pix[mainPos + 3] > 0){ if(firstX < x){ firstX = x; } if(y < firstY){ firstY = y; } if(lastX >x){ lastX = x; } if(lastY < y){ lastY = y; } } } } currentImage.setFromPixels(newPix, width,height, OF_IMAGE_COLOR_ALPHA, true); lastFrame = currentFrame; int xl = 0; int xw = 0; int yl = 0; int yw = 0; if(lastX < firstX){ xl = lastX; xw = firstX - lastX; } else { xl = firstX; xw = lastX - firstX; } if(lastY < firstY){ yl = lastY; yw = firstY - lastY; } else { yl = firstY; yw = lastY - firstY; } boundingBox = ofRectangle(xl * scale ,yl *scale , xw * scale, yw * scale); delete[] newPix; } }
void ofx2DMapping::setControlShape(float x, float y, float width, float height) { view.setShape(ofRectangle(x,y,width,height)); ctrl.setControlWidth(width); ctrl.setControlHeight(height); }
//-------------------------------------------------------------- void ofApp::update(){ // 削除 // rects // int rectLifeTime = 30; // for (int i=0; i<rects.size(); i++) { // if (ofGetElapsedTimef() - rects[i]->getBirthTime() > rectLifeTime) { // rects.erase(rects.begin()+i); // } // } // circles // ofRemove(rects, removeShapeOffScreen); // custom rect // ofRemove(circles, removeShapeOffScreen); // custom circle for (int i=0; i<circles.size(); i++) { if (ofGetElapsedTimef() - circles[i]->getBirthTime() > circleLifeTime) { circles.erase(circles.begin()+i); } if (!ofRectangle(0, -400, ofGetWidth(), ofGetHeight()+400).inside(circles[i]->getPosition())) { circles.erase(circles.begin()+i); } } // circle logos for (int i=0; i<circleLogos.size(); i++) { if (ofGetElapsedTimef() - circleLogos[i]->getBirthTime() > circleLogosLifeTime) { circleLogos.erase(circleLogos.begin()+i); } if (!ofRectangle(0, -400, ofGetWidth(), ofGetHeight()+400).inside(circleLogos[i]->getPosition())) { circleLogos.erase(circleLogos.begin()+i); } } // special circle // if (!ofRectangle(0, -400, ofGetWidth(), ofGetHeight()+400).inside(specialCircle->getPosition())) { // specialCircle->setPosition(ofRandom(0, ofGetWidth()), ofRandom(-ofGetHeight()/3.0, 0)); // } box2d.setGravity(0, gravity); box2d.update(); //追加 // rects // if (rects.size() < 30) { // rects.push_back(ofPtr<CustomRect>(new CustomRect)); // rects.back().get()->setPhysics(0.2, 0.0, 3.9); // // widthをキーにして、比率を守って、高さを決定する // int photoIdRect = rand()%photoNumberRect; // float logoArea = ofRandom(1000, 10000); // // float w = sqrt(logoArea*customRectImageVector[photoIdRect].getWidth()/customRectImageVector[photoIdRect].getHeight()); // float h = logoArea/w; //// float h = w*customRectImageVector[photoId].getHeight()/customRectImageVector[photoId].getWidth(); // rects.back().get()->setup(box2d.getWorld(), ofGetWidth()/2.+ofRandom(-ofGetWidth()/2.*0.5, ofGetWidth()/2.*0.5), ofRandom(-ofGetHeight()/3.0, -customRectImageVector[photoIdRect].getHeight()), w, h); // rects.back().get()->setImage(customRectImageVector[photoIdRect]); // rects.back().get()->setBirthTime(ofGetElapsedTimef()); // } // circles // if (circles.size() < circleNumberLimit) { // circles.push_back(ofPtr<CustomCircle>(new CustomCircle)); // circles.back().get()->setCircleMainColor(ofColor(ofRandom(0, 255), ofRandom(0, 255), ofRandom(0, 255), 127)); // circles.back().get()->setBirthTime(ofGetElapsedTimef()); // circles.back().get()->setPhysics(0.02, 0.0, 3.9); // float radius = ofRandom(circleSizeRangeMinimum, circleSizeRangeMaximum); // circles.back().get()->setStandardRadius(radius); // circles.back().get()->setRadiusChangeSpeed(ofRandom(0, 0.15)); // circles.back().get()->setRadiusChangeAngle(ofRandom(0, TWO_PI)); // circles.back().get()->setup(box2d.getWorld(), ofRandom(0, ofGetWidth()), ofRandom(-ofGetHeight()/3.0, -radius), radius); // } // circle logos if (circleLogos.size() < circleLogoNumberLimit) { circleLogos.push_back(ofPtr<CustomCircle>(new CustomCircle)); circleLogos.back().get()->setCircleMainColor(ofColor(ofRandom(0, 255), ofRandom(0, 255), ofRandom(0, 255), 0)); circleLogos.back().get()->setBirthTime(ofGetElapsedTimef()); float radius = ofRandom(circleLogoSizeRangeMinimum, circleLogoSizeRangeMaximum); int photoId = rand()%photoNumberCircleLogos; circleLogos.back().get()->setImage(customCircleImageVector[photoId]); circleLogos.back().get()->setPhysics(0.01, 0.0, 3.9); circleLogos.back().get()->setup(box2d.getWorld(), ofRandom(0, ofGetWidth()), ofRandom(-ofGetHeight()/3.0, -radius), radius); } // 色を変える // specialCircle->setCircleMainColor(ofColor(ofRandom(0, 255), ofRandom(0, 255), ofRandom(0, 255), 127)); //camera if (useBlackMagic) { if(blackMagic.update()) { timer.tick(); } }else{ vidGrabber.update(); } if(useBlackMagic || vidGrabber.isFrameNew()){ //フレームが切り替わった際のみ画像を解析 //取り込んだフレームを画像としてキャプチャ if (useBlackMagic) { colorImg.setFromPixels(blackMagic.getColorPixels()); }else{ colorImg.setFromPixels(vidGrabber.getPixelsRef()); } //ADJUSTME: 上下・左右反転() colorImg.mirror(false, true); //カラーのイメージをグレースケールに変換 grayImage = colorImg; //まだ背景画像が記録されていなければ、現在のフレームを背景画像とする if (bLearnBakground == true){ grayBg = grayImage; bLearnBakground = false; } //グレースケールのイメージと取り込んだ背景画像との差分を算出 grayDiff.absDiff(grayBg, grayImage); //画像を2値化(白と黒だけに)する grayDiff.threshold(threshold); //縮小した差分イメージに画像をコピー grayDiffSmall.scaleIntoMe(grayDiff); //ぼかし grayDiffSmall.blur(5); //ベクトル場に差分イメージを適用 VF.setFromPixels(grayDiffSmall.getPixels(), bForceInward, 0.05f); //更新 //ベクトル場に発生した力を計算し、パーティクルにかかる力を算出 //particles // for(list <CustomCircle *>::iterator it = particles.begin(); it != particles.end(); ++it){ // ofVec2f frc; // frc = VF.getForceFromPos((*it)->getPosition().x, (*it)->getPosition().y); // //設定した閾値を越えたら、VFの力を加える // if (frc.length() > vectorThreshold) { // (*it)->addForce(ofPoint(frc.x * force, frc.y * force), 1.0); // } // (*it)->update(); // } //同様にcustom rectに対しても // for (int i = 0; i<rects.size(); i++) { // ofVec2f frc; // frc = VF.getForceFromPos(rects[i]->getPosition().x, rects[i]->getPosition().y); // //設定した閾値を越えたら、VFの力を加える // if (frc.length() > vectorThreshold) { // rects[i]->addForce(ofPoint(frc.x * force, frc.y * force), 1.0); // } // rects[i]->update(); // } //同様にcustom circlesに対しても // for (int i = 0; i<circles.size(); i++){ // // サイズを変更 // circles[i]->setRadiusChangeAngle(circles[i]->getRadiusChangeAngle()+circles[i]->getRadiusChangeSpeed()); // if (circles[i]->getRadiusChangeAngle()>TWO_PI) { // circles[i]->setRadiusChangeAngle(circles[i]->getRadiusChangeAngle()-TWO_PI); // } // circles[i]->setRadius(circles[i]->getStandardRadius()*((sin(circles[i]->getRadiusChangeAngle())+1)/2.0+0.5)); // // // 物理演算 // ofVec2f frc; // frc = VF.getForceFromPos(circles[i]->getPosition().x, circles[i]->getPosition().y); // //設定した閾値を越えたら、VFの力を加える // if (frc.length() > vectorThreshold) { // circles[i]->addForce(ofPoint(frc.x * force, frc.y * force), 1.0); // } // circles[i]->update(); // } //同様にcustom circles logoに対しても for (int i = 0; i<circleLogos.size(); i++){ ofVec2f frc; frc = VF.getForceFromPos(circleLogos[i]->getPosition().x, circleLogos[i]->getPosition().y); //設定した閾値を越えたら、VFの力を加える if (frc.length() > vectorThreshold) { circleLogos[i]->addForce(ofPoint(frc.x * force, frc.y * force), 1.0); } circleLogos[i]->update(); } //同様にspecial circles logoに対しても // ofVec2f frc; // frc = VF.getForceFromPos(specialCircle->getPosition().x, specialCircle->getPosition().y); // //設定した閾値を越えたら、VFの力を加える // if (frc.length() > vectorThreshold) { // specialCircle->addForce(ofPoint(frc.x * force, frc.y * force), 1.0); // } // specialCircle->update(); } }
void TextWriter::draw(ofRectangle box, string text, bool centred) { text = ofToUpper(text); // added these lines otherwise you get horribleness! if(box.height<=0) box.height = 1; if(box.width<=0) box.width = 1; ofPushStyle(); ofEnableAlphaBlending(); ofEnableBlendMode(OF_BLENDMODE_ADD); ofSetLineWidth(glyphLineWeight); ofPushStyle(); ofSetColor(10, 10, 255, 128); ofNoFill(); ofPopStyle(); float boxRatio = box.height / (float)box.width; int textLength = text.length(); string longestLine = ""; vector<string> lines; int numRows = (int)sqrt(boxRatio * textLength / glyphRatio); if( (text.find(' ') == string::npos) || (numRows == 0) ) { longestLine = trim(text); lines.push_back(longestLine); } else { int numCols = textLength / numRows; int start = numCols; int index = 0; int last; for( int row = 0; row < numRows - 1; row++ ) { last = index; index = findBestBreak(text, start, numCols * 2); string linePart = trim(text.substr(last, index - last)); if( linePart.length() > longestLine.length() ) { longestLine = linePart; } lines.push_back(linePart); start = index + numCols; } string linePart = trim(text.substr(index)); lines.push_back(linePart); if( linePart.length() > longestLine.length() ) { longestLine = linePart; } } float glyphScaleFactor = (box.width / (float)longestLine.length()) / (float)(glyphWidth + glyphSpacing); float glyphRenderWidth = glyphWidth * glyphScaleFactor; float glyphRenderHeight = glyphHeight * glyphScaleFactor; float glyphRenderSpacing = glyphSpacing * glyphScaleFactor; float marginTop = ((box.height - ((glyphRenderHeight + glyphRenderSpacing) * lines.size())) / 2.0); float marginLeft = 0; //(int)((box.width - calculateBlockWidth(longestLine, glyphRenderWidth, glyphRenderSpacing)) / 2.0); map <int, Letter>& letters = font.letters; ofMesh writingMesh; float ofsX = marginLeft, ofsY = marginTop; for( int j = 0; j < lines.size(); j++ ) { string line = lines[j]; float glyphMarginLeft = centred ? ((box.width - calculateBlockWidth(line, glyphRenderWidth, glyphRenderSpacing)) / 2.0) : 0; for( int i = 0; i < line.length(); i++ ) { addGlyphToMesh(letters[line[i]], ofRectangle(box.x + ofsX + glyphMarginLeft, box.y + ofsY, glyphRenderWidth, glyphRenderHeight), writingMesh); ofsX += glyphRenderWidth + glyphRenderSpacing; } ofsX = marginLeft; ofsY += glyphRenderHeight + glyphRenderSpacing; } writingMesh.setMode(OF_PRIMITIVE_LINES); writingMesh.draw(); writingMesh.setMode(OF_PRIMITIVE_POINTS); writingMesh.draw(); ofPopStyle(); return writingMesh; }
void ofx2DMapping::setOutputShape(float x, float y, float width, float height) { ctrl.setOutputRectangle(ofRectangle(x,y,width,height)); view.getFormMapping()->setOutputForm(x,y,width,height); }
static bool shouldRemove(shared_ptr<ofxBox2dBaseShape>shape) { return !ofRectangle(0, -400, ofGetWidth(), ofGetHeight()+400).inside(shape->getPosition()); }
void CloudsRGBDVideoPlayer::swapAndPlay(){ cout << "*** SWAPPING CLIP" << endl; if(!nextClipIsVO){ ofxXmlSettings XML; if ( !XML.loadFile(nextCalibrationXML) ){ ofLogError("CloudsRGBDVideoPlayer::setup") << "XML Path " << nextCalibrationXML << " failed to load"; return; } colorPrincipalPoint.x = XML.getValue("colorIntrinsics:ppx", 971.743835449); colorPrincipalPoint.y = XML.getValue("colorIntrinsics:ppy", 546.945983887); colorFOV.x = XML.getValue("colorIntrinsics:fovx", 923.500793457); colorFOV.y = XML.getValue("colorIntrinsics:fovy", 921.060791016); colorRect.x = 0.0f; colorRect.y = 0.0f; colorRect.width = XML.getValue("colorIntrinsics:width", 1920.000000000); colorRect.height = XML.getValue("colorIntrinsics:height", 1080.000000000); float depthToRGBRotation[9]; float depthToRGBTranslation[3]; for (int i = 0; i < 9; i++) { depthToRGBRotation[i] = XML.getValue("extrinsics:rotation:r"+ofToString(i), 1.0f); } for (int i = 0; i < 3; i++) { depthToRGBTranslation[i] = XML.getValue("extrinsics:translation:t"+ofToString(i), 1.0f); } for (int i = 0; i < 3; i++) { distortionK[i] = XML.getValue("colorIntrinsics:dK:k"+ofToString(i), 1.0f); } for (int i = 0; i < 2; i++) { distortionP[i] = XML.getValue("colorIntrinsics:dP:p"+ofToString(i), 1.0f); } headPosition = ofVec3f(-XML.getValue("face:x", 0.0), -XML.getValue("face:y", 0.0), XML.getValue("face:z", 0.0)); //cout << "head position " << headPosition << endl; float mat4x4[16] = { depthToRGBRotation[0],depthToRGBRotation[1],depthToRGBRotation[2],0, depthToRGBRotation[3],depthToRGBRotation[4],depthToRGBRotation[5],0, depthToRGBRotation[6],depthToRGBRotation[7],depthToRGBRotation[8],0, depthToRGBTranslation[0],depthToRGBTranslation[1],depthToRGBTranslation[2],1 }; extrinsics = ofMatrix4x4(mat4x4); // cout << "extrinsic matrix: " << endl << extrinsics << endl; //adjustment adjustTranslate.x = XML.getValue("adjustment:translate:x", 0.0); adjustTranslate.y = XML.getValue("adjustment:translate:y", 0.0); adjustTranslate.z = XML.getValue("adjustment:translate:z", 0.0); adjustRotate.x = XML.getValue("adjustment:rotate:x", 0.0); adjustRotate.y = XML.getValue("adjustment:rotate:y", 0.0); adjustRotate.z = XML.getValue("adjustment:rotate:z", 0.0); adjustScale.x = XML.getValue("adjustment:scale:x", 1.0); adjustScale.y = XML.getValue("adjustment:scale:y", 1.0); depthPrincipalPoint.x = XML.getValue("depthIntrinsics:ppx", 320.0); depthPrincipalPoint.y = XML.getValue("depthIntrinsics:ppy", 240.0); depthFOV.x = XML.getValue("depthIntrinsics:fovx", 570.34); depthFOV.y = XML.getValue("depthIntrinsics:fovy", 570.34); depthRect.x = 0.0; // TODO: do this automatically depthRect.y = 720.0; // depthRect.width = XML.getValue("depthIntrinsics:width", 640.0); depthRect.height = XML.getValue("depthIntrinsics:height", 480.0); normalRect.x = 640.0; // TODO: do this automatically normalRect.y = 720.0; // normalRect.width = 640.0; normalRect.height = 480.0; nearClip = minDepth = XML.getValue("adjustment:depth:min", 1.0f); farClip = maxDepth = XML.getValue("adjustment:depth:max", 6000.0f); ////////-----NO LONGER USED //this describes the face features: eyes, mouth, and skin faceFeatureRect = ofRectangle(depthRect.x, depthRect.getMaxY(), 640, 360); //this describes the change each frame deltaChangeRect = ofRectangle(normalRect.x, normalRect.getMaxY(), 640, 360); //////////// hasSkinSettings = XML.tagExists("skin"); skinSampleColor.r = XML.getValue("skin:targetR", 0.); skinSampleColor.g = XML.getValue("skin:targetG", 0.); skinSampleColor.b = XML.getValue("skin:targetB", 0.); skinWeights.x = XML.getValue("skin:hueWeight", 0.); skinWeights.y = XML.getValue("skin:satWeight", 0.); skinWeights.z = XML.getValue("skin:brightWeight", 0.); skinThreshold.min = XML.getValue("skin:lowerThreshold", .0); skinThreshold.max = XML.getValue("skin:upperThreshold", 1.0); // cout << "HAS SKIN? " << hasSkinSettings << endl; // float colorWidth = getPlayer().getWidth(); // float colorHeight = getPlayer().getHeight(); float colorWidth = 1280; float colorHeight = 1560; colorScale.x = colorWidth / colorRect.width; colorScale.y = float(colorHeight - (depthRect.height + faceFeatureRect.height) ) / float(colorRect.height); useFaces = true; } if(clipPrerolled){ if(bLoadResult){ cout << "*** STARTING PLAYER FROM SWAP" << endl; startPlayer(); } else{ bPlayWhenReady = true; } } }
//-------------------------------------------------------------- void storeApp::update() { double timestamp = ofGetElapsedTimeMillis(); while(receiver.hasWaitingMessages() ) { // get the next message ofxOscMessage m; receiver.getNextMessage( &m ); if ( m.getAddress() == "/test" ) { } else if ( m.getAddress() == "/tweet" ) { if (m.getNumArgs() >= 2) { string user = ""; if (m.getArgType(0) == OFXOSC_TYPE_STRING) { user = m.getArgAsString(0); } string text = ""; if (m.getArgType(1) == OFXOSC_TYPE_STRING) { text = m.getArgAsString(1); } if (user != "" && text!= "") { //ofDrawBitmapString( user + ": " + text, 80, 200 ); //tweet = user + ": " + text; if (tweets->tweets->size() < 100) { tweets->push(new Tweet(user, text)); } } } } } if (ofGetElapsedTimeMillis() - timestamp > 10) cout << "msg parsed in " << ofGetElapsedTimeMillis() - timestamp << endl; if (ofGetElapsedTimeMillis() - lastTweetTime > 200) { if (tweets->tweets->size() > 0) { float margin = 20; Tweet *t = tweets->pop(); string text = t->getUser() + ": " + t->getText(); timestamp = ofGetElapsedTimeMillis(); Tweet *newTweet = new Tweet(t->getUser(), t->getText()); newTweet->textBlock.init(&defaultFont, &doubleSizedFont, &superSizedFont); newTweet->textBlock.setText(text); newTweet->textBlock.wrapTextInWidthHM(ofGetWidth()/6 - margin*2); newTweet->textBlock.setColor(255, 255, 255, 255); newTweet->bound = ofRectangle( activeColumn * ofGetWidth()/6 + margin, margin, ofGetWidth()/6 - margin * 2, ofGetHeight() - margin * 2 ); newTweet->lastShownTime = ofGetElapsedTimeMillis(); newTweet->live = true; tweetsOnShow->push(newTweet); //cout << "tweets on show: " << tweetsOnShow->tweets->size() << endl; tweets->tweets->pop_front(); activeColumn = (activeColumn+1) % 6; if (tweetsOnShow->tweets->size() > 6) { tweetsOnShow->tweets->pop_front(); } lastTweetTime = ofGetElapsedTimeMillis(); cout << "new tweet init'd in " << ofGetElapsedTimeMillis() - timestamp << endl; //cout << tweets->tweets->size(); //cout << " tweet in queue\n"; } } }
void EnsancheModelBuildingAdv::draw3D2(bool bDrawWOffset) { //cout << "draw 3d2" << endl; float tx0 = 0; float ty0 = 0; float tx1 = (bSetWallTexture) ? 2.5*textureWall->texData.tex_t : 1; float ty1 = (bSetWallTexture) ? textureWall->texData.tex_u : 1; float tempPts[13]; memset(tempPts, 0, 13*sizeof(float)); float tempTexpts[9]; memset(tempTexpts, 0, 9*sizeof(float)); // leave, maybe need offset later?? ofRectangle boundingBox = ofRectangle(0,0,0,0); float wallHeight = -EN_FLOOR_HEIGHT; glPushMatrix(); if( bDrawWOffset) glTranslatef(offSet.x,0.f,offSet.y); glTranslatef(center.x,center.y,center.z); glScalef(scale,scale,scale); glRotatef(rotation.x,1,0,0); glRotatef(rotation.y,0,1,0); glRotatef(rotation.z,0,0,1); glTranslatef(-center.x,-center.y,-center.z); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); ofSetColor(255, 255, 255,255); for( int i = 0; i < buildingFloors.size(); i++) { if( wallTexIds.size() < i ){ cout << "wallTexIds.size()" << wallTexIds.size() << " buildingFloors.size() " << buildingFloors.size() << endl; continue; } for( int j = 0; j < buildingFloors[i].pts.size()-1; j++) { int tnpts = 0; int ntexpts = 0; tempPts[ tnpts ] = buildingFloors[i].pts[j].x-boundingBox.x; tempPts[ tnpts+1] = i * wallHeight; tempPts[ tnpts+2] = buildingFloors[i].pts[j].y-boundingBox.y; tnpts += 3; tempPts[ tnpts ] = buildingFloors[i].pts[j+1].x-boundingBox.x; tempPts[ tnpts+1] = i * wallHeight; tempPts[ tnpts+2] = buildingFloors[i].pts[j+1].y-boundingBox.y; tnpts += 3; tempPts[ tnpts] = buildingFloors[i].pts[j+1].x-boundingBox.x; tempPts[ tnpts+1] = (i * wallHeight)+wallHeight; tempPts[ tnpts+2] = buildingFloors[i].pts[j+1].y-boundingBox.y; tnpts += 3; tempPts[ tnpts] = buildingFloors[i].pts[j].x-boundingBox.x; tempPts[ tnpts+1] = (i * wallHeight)+wallHeight; tempPts[ tnpts+2] = buildingFloors[i].pts[j].y-boundingBox.y; tnpts += 3; int total = (int)(tnpts/3.f); // get len wall float len = sqrt( (buildingFloors[i].pts[j].x-buildingFloors[i].pts[j+1].x)*(buildingFloors[i].pts[j].x-buildingFloors[i].pts[j+1].x) + (buildingFloors[i].pts[j].y-buildingFloors[i].pts[j+1].y)*(buildingFloors[i].pts[j].y-buildingFloors[i].pts[j+1].y) ); float pct = len / 4.f; tempTexpts[ ntexpts ] = tx0; tempTexpts[ ntexpts+1] = ty0; tempTexpts[ ntexpts+2] = pct*tx1; tempTexpts[ ntexpts+3] = ty0; tempTexpts[ ntexpts+4] = pct*tx1; tempTexpts[ ntexpts+5] = 2*ty1; tempTexpts[ ntexpts+6] = tx0; tempTexpts[ ntexpts+7] = 2*ty1; ntexpts+= 8; int texID = (wallTexIds[i].tId.size()>j) ? wallTexIds[i].tId[j] : 0; if(bSetWallTextures[texID]){ //textureWall->setTextureWrap(GL_REPEAT, GL_REPEAT); glEnable(textureWalls[texID]->texData.textureTarget); // bind the texture glBindTexture( textureWalls[texID]->texData.textureTarget, (GLuint)textureWalls[texID]->texData.textureID ); glTexParameterf(textureWalls[texID]->texData.textureTarget, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(textureWalls[texID]->texData.textureTarget, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexCoordPointer(2, GL_FLOAT, 0, tempTexpts); } glVertexPointer(3, GL_FLOAT, 0, tempPts); glDrawArrays(GL_QUADS, 0, total); } //if(bSetWallTextures[i]) glDisableClientState( GL_TEXTURE_COORD_ARRAY ); //cout << "id " << " nptsv: " << nptsv[id] << " nTotalPts[id] " << nTotalPts[id] << endl; } //if(bSetWallTextures[i]) glDisableClientState( GL_TEXTURE_COORD_ARRAY ); glDisableClientState(GL_VERTEX_ARRAY); // ceilings ofFill(); //ofSetColor(255, 0, 0,255); for( int i = 0; i < buildingFloors.size(); i++) { //ofRectangle bb = buildingFloors[i].getBoundingBox(); glPushMatrix(); glBegin(GL_POLYGON); for( int j = 0; j < buildingFloors[i].pts.size();j++) glVertex3f(buildingFloors[i].pts[j].x, -(i+1)*EN_FLOOR_HEIGHT, buildingFloors[i].pts[j].y); glEnd(); glPopMatrix(); /* ofBeginShape(true); for( int j = 0; j < buildingFloors[i].pts.size();j++) { ofVertex(buildingFloors[i].pts[j].x, (i+1)*EN_FLOOR_HEIGHT, buildingFloors[i].pts[j].y); } ofEndShape(true,true);*/ } glPopMatrix(); }
static bool removeShapeOffScreen(ofPtr<ofxBox2dBaseShape> shape) { if (!ofRectangle(0, -400, ofGetWidth(), ofGetHeight()+400).inside(shape.get()->getPosition())) { return true; } return false; }
void EnsancheModelBuildingAdv::generateModel( float wallHeight ) { return; //!! NOTE check if this is ok for delete other arrays!! for( int i = 0; i < MODEL_T_TEXTURES; i++) { if(nptsv[i] > 0) delete [] ptsv[i]; if(ntexptsv[i] > 0) delete [] texptsv[i]; } // memset the totals memset(nptsv,0,MODEL_T_TEXTURES*sizeof(int)); memset(ntexptsv,0,MODEL_T_TEXTURES*sizeof(int)); // y inverted if(wallHeight > 0 ) wallHeight *= -1; // set the center y position of model center.y = (buildingFloors.size()*wallHeight ) * .5; // calculate totatls for each type of texture for( int i = 0; i < wallTexIds.size(); i++) { cout << "i: " << i << " wallTexIds[i].tId.size() " << wallTexIds[i].tId.size() << endl; for( int j = 0; j < wallTexIds[i].tId.size(); j++) { int id = wallTexIds[i].tId[j]; if( id >= MODEL_T_TEXTURES ) id = 0; nptsv[id]++; ntexptsv[id]++; } } // multiply so includes memory for 4 corners of quad and 3 coordinates, 2 coord for texture for( int i = 0; i < MODEL_T_TEXTURES; i++) { nptsv[i] = (nptsv[i]*4)*3; ntexptsv[i] = (ntexptsv[i]*4)*2; } // allocate memory for pts for textures int nTotalPts[4]; int nTotalTxPts[4]; for( int i = 0; i < MODEL_T_TEXTURES; i++) { nTotalPts[i] = nptsv[i] ; nTotalTxPts[i] = ntexptsv[i]; if(nptsv[i]>0) { ptsv[i] = new float[ nptsv[i] ]; texptsv[i] = new float[ ntexptsv[i] ]; } } memset(nptsv,0,MODEL_T_TEXTURES*sizeof(int)); memset(ntexptsv,0,MODEL_T_TEXTURES*sizeof(int)); // leave, maybe need offset later?? ofRectangle boundingBox = ofRectangle(0,0,0,0); // create pts for( int i = 0; i < buildingFloors.size(); i++) { if( wallTexIds.size() < i ){ cout << "wallTexIds.size()" << wallTexIds.size() << " buildingFloors.size() " << buildingFloors.size() << endl; continue; } for( int j = 0; j < buildingFloors[i].pts.size()-1; j++) { if( wallTexIds[i].tId.size() < j+1 ){ cout << "wallTexIds[i].tId.size() < j+1 " << (j+1) << endl; continue; } int id = wallTexIds[i].tId[j]; if( id >= MODEL_T_TEXTURES || id < 0 ) id = 0; //cout << "i: " << i << " j: " << j << "id " << id << " walltype " << wallTexIds[i].tId[j] << endl; //cout << "id " << " nptsv: " << nptsv[id] << " nTotalPts[id] " << nTotalPts[id] << endl; if(nptsv[id]+12 > nTotalPts[id]){ cout << "nptsv[id]+12 " << nptsv[id]+12 << " nTotalPts[id] " << nTotalPts[id] << endl; continue; } ptsv[id][ nptsv[id] ] = buildingFloors[i].pts[j].x-boundingBox.x; ptsv[id][ nptsv[id]+1] = i * wallHeight; ptsv[id][ nptsv[id]+2] = buildingFloors[i].pts[j].y-boundingBox.y; nptsv[id] += 3; ptsv[id][ nptsv[id]] = buildingFloors[i].pts[j+1].x-boundingBox.x; ptsv[id][ nptsv[id]+1] = i * wallHeight; ptsv[id][ nptsv[id]+2] = buildingFloors[i].pts[j+1].y-boundingBox.y; nptsv[id] += 3; ptsv[id][ nptsv[id]] = buildingFloors[i].pts[j+1].x-boundingBox.x; ptsv[id][ nptsv[id]+1] = (i * wallHeight)+wallHeight; ptsv[id][ nptsv[id]+2] = buildingFloors[i].pts[j+1].y-boundingBox.y; nptsv[id] += 3; ptsv[id][ nptsv[id]] = buildingFloors[i].pts[j].x-boundingBox.x; ptsv[id][ nptsv[id]+1] = (i * wallHeight)+wallHeight; ptsv[id][ nptsv[id]+2] = buildingFloors[i].pts[j].y-boundingBox.y; nptsv[id] += 3; } //cout << "id " << " nptsv: " << nptsv[id] << " nTotalPts[id] " << nTotalPts[id] << endl; } float tx0 = 0; float ty0 = 0; float tx1 = (bSetWallTexture) ? 2.5*textureWall->texData.tex_t : 1; float ty1 = (bSetWallTexture) ? textureWall->texData.tex_u : 1; // create texture pts for( int i = 0; i < buildingFloors.size(); i++) { if( wallTexIds.size() < i ) continue; for( int j = 0; j < buildingFloors[i].pts.size()-1; j++) { if( wallTexIds[i].tId.size() < j+1 ) continue; int id = wallTexIds[i].tId[j]; if( id >= MODEL_T_TEXTURES || id < 0 ) id = 0; // get len wall float len = sqrt( (buildingFloors[i].pts[j].x-buildingFloors[i].pts[j+1].x)*(buildingFloors[i].pts[j].x-buildingFloors[i].pts[j+1].x) + (buildingFloors[i].pts[j].y-buildingFloors[i].pts[j+1].y)*(buildingFloors[i].pts[j].y-buildingFloors[i].pts[j+1].y) ); float pct = len / 4.f; texptsv[id][ ntexptsv[id] ] = tx0; texptsv[id][ ntexptsv[id]+1] = ty0; texptsv[id][ ntexptsv[id]+2] = pct*tx1; texptsv[id][ ntexptsv[id]+3] = ty0; texptsv[id][ ntexptsv[id]+4] = pct*tx1; texptsv[id][ ntexptsv[id]+5] = 2*ty1; texptsv[id][ ntexptsv[id]+6] = tx0; texptsv[id][ ntexptsv[id]+7] = 2*ty1; ntexptsv[id]+= 8; } } }
void ofxCvCheckerboardPreview::draw() { draw(ofRectangle(0,0,testImage.getWidth(), testImage.getHeight()) ); }
//----------------------------------------------- void guiTypePanel::addColumn(float minWidth){ float colX = columns.back().x + columns.back().width + spacingAmntX; columns.push_back(ofRectangle(colX, currentYPos, minWidth, 20)); }
void ofxCvCheckerboardPreview::draw(float x, float y) { draw(ofRectangle(x,y,testImage.getWidth(), testImage.getHeight() )); }
//-------------------------------------------------------------- void AppCore::draw() { float marge = width * .05f; reader->draw(ofRectangle(width * .5f + marge, marge, width * .5f - 2.f * marge, height - 2.f * marge), &font); for (int i = widgets.size() - 1; i > -1; i--) widgets[i]->draw(); }
void ofxCvCheckerboardPreview::draw(ofVec2f point) { draw(ofRectangle(point.x,point.y,testImage.getWidth(), testImage.getHeight() )); }
void StCvOpMeshColor::update(){ //CV params ofxUISlider *p = (ofxUISlider *)gui->getWidget("PYR SCALE"); pyrScale = p->getValue(); ofxUIIntSlider *l = (ofxUIIntSlider *)gui->getWidget("LEVELS"); levels = l->getValue(); ofxUIIntSlider *w = (ofxUIIntSlider *)gui->getWidget("WIN SIZE"); winsize = w->getValue(); ofxUIIntSlider *it = (ofxUIIntSlider *)gui->getWidget("ITERATION"); iterations = it->getValue(); ofxUIToggle *gs = (ofxUIToggle *)gui->getWidget("GAUSS"); OPTFLOW_FARNEBACK_GAUSSIAN = gs->getValue(); polyN = 7; polySigma = 1.5; ofPixelsRef pix = ((ofApp*)ofGetAppPtr())->blackmagic->colorPixels; pix.resize(160, 90); flow.setPyramidScale(pyrScale); flow.setNumLevels(levels); flow.setWindowSize(winsize); flow.setNumIterations(iterations); flow.setPolyN(polyN); flow.setPolySigma(polySigma); flow.setUseGaussian(OPTFLOW_FARNEBACK_GAUSSIAN); if (pix.size() > 0) { flow.calcOpticalFlow(pix); } ofxUISlider *gthresh = (ofxUISlider *)gui->getWidget("THRESH"); float thresh = gthresh->getValue(); ofxUISlider *gskip = (ofxUISlider *)gui->getWidget("SKIP"); float skip = gskip->getValue(); ofxUISlider *gaccel = (ofxUISlider *)gui->getWidget("ACCEL"); float accel = gaccel->getValue(); ofxUISlider *gwind = (ofxUISlider *)gui->getWidget("WIND"); float wind = gwind->getValue(); ofxUISlider *gfriction = (ofxUISlider *)gui->getWidget("FRICTION"); float friction = gfriction->getValue(); ofxUISlider *ghue = (ofxUISlider *)gui->getWidget("HUE"); float hue = ghue->getValue(); ofxUISlider *gsat = (ofxUISlider *)gui->getWidget("SAT"); float sat = gsat->getValue(); ofxUISlider *gbr = (ofxUISlider *)gui->getWidget("BR"); float br = gbr->getValue(); for (int i = 0; i < particles.size(); i++) { float ratio = SCREEN_WIDTH / (pix.getWidth() - skip * 6); int x = particles[i]->position.x / ratio + (skip * 2); int y = particles[i]->position.y / ratio + (skip * 2); particles[i]->resetForce(); particles[i]->friction = friction / 100.0; ofVec2f force; if (x > 0 && y > 0 && x < flow.getWidth() - skip && y < flow.getHeight() - skip) { ofRectangle region = ofRectangle(x, y, skip, skip); force = flow.getAverageFlowInRegion(region); } // wind force += ofVec3f(wind, wind * 0.1, 0.0); particles[i]->addForce(force * accel); particles[i]->updateForce(); particles[i]->updatePos(); particles[i]->throughOfWalls(); ofColor col = pix.getColor(x + skip * 2, y); float controlHue; controlHue = ofMap(app->oscControl->controlVal[5], 0, 127, 1.125, 0.7); int h = controlHue; col.setHsb(int(controlHue * 255) % 255, 255, 255); /* float controlRB; controlRB = ofMap(app->oscControl->controlVal[5], 0, 127, 0, 1.0); col.set(255 - controlRB * 255, 0, controlRB * 255); */ particles[i]->col = col; } gui->setVisible(getSharedData().guiVisible); }
void ofxTextLabel_<T>::setup(T * font, const string& text, float lineLength, float lineSpacing, ofAlignHorz alignHorz, ofAlignVert alignVert) { setup(font, text, ofRectangle(0, 0, lineLength, 0), lineSpacing, alignHorz, alignVert); }
void nebulaEye::draw() { int w=ofGetWidth(), h=ofGetHeight(); if ( ( ofGetHeight() > 0 && img.getHeight() > 0 ) ) { if ( ofGetWidth()/ofGetHeight() > img.getWidth()/img.getHeight()){ h = ofGetHeight(); w = h * img.getWidth()/img.getHeight(); } else if (img.getWidth()>0){ w = ofGetWidth(); h = w * img.getHeight()/img.getWidth(); } } ofSetColor(255,255,255); if(showVideo){ if (mouseTest){ ofxCv::drawMat(testimg,0,0); } else { video.draw(0,0,w,h); } } if(showBgSub){ ofSetColor(255,255,255,bgSubIntensity); bgSub.draw(0,0,w,h); } if(showFlow){ ofSetColor(0,255,0,255); flow.draw(0,0,w, h); } if(showContour){ ofSetColor(255,255,255); contour.draw(0,0,w,h); } if(showZone){ ofSetColor(255,0,0,64); zone.draw(); } if (showDebug){ ofSetColor(255); int i = showDebug.get()-1; if ( i < zone.mask.size() ){ ofRectangle rect = ofRectangle(zone.mask[i].cols/2,zone.mask[i].rows/2, zone.mask[i].cols, zone.mask[i].rows); ofxCv::drawMat(zone.mask[i],rect.x, rect.y); cv::Mat m_flow; double zoneFlow = flow.getFlowInMask(zone.mask[i], &m_flow); ofVec2f offset(rect.x,rect.y); ofVec2f scale(rect.width/m_flow.cols, rect.height/m_flow.rows); int stepSize = 4; ofPopStyle(); ofSetColor(0,255,0); for(int y = 0; y < m_flow.rows; y += stepSize) { for(int x = 0; x < m_flow.cols; x += stepSize) { ofVec2f cur = ofVec2f(x, y) * scale + offset; const cv::Vec2f& vec = m_flow.at<cv::Vec2f>(y, x); ofDrawLine(cur, ofVec2f(x + vec[0], y + vec[1]) * scale + offset); } } ofPushStyle(); stringstream ss; ss << "zone flow : " << zoneFlow; ofDrawBitmapString(ss.str(), ofPoint(rect.x+10,rect.y-10)); } else { ofRectangle rect = ofRectangle(bgSub.m_fgmask.cols/2,bgSub.m_fgmask.rows/2, bgSub.m_fgmask.cols, bgSub.m_fgmask.rows); ofxCv::drawMat(contour.blurred,rect.x, rect.y); } } if (showGui){ gui.draw(); } recordPanel.draw(); }
//-------------------------------------------------------------- void gFrameApp::setup() { //just set up the openFrameworks stuff ofSetFrameRate(60); ofSetVerticalSync(true); ofBackground(ofColor::black); //LEDFrame setup ledFrame.setup(); //GUI setup guiSetup(); styleGuiSetup(); //eventhamdlers for gui ofAddListener(gui.loadPressedE, this, &gFrameApp::onSettingsReload); ofAddListener(gui.savePressedE, this, &gFrameApp::onSettingsSave); ofAddListener(style_gui.loadPressedE, this, &gFrameApp::onStyleSettingsreload); ofAddListener(style_gui.savePressedE, this, &gFrameApp::onStyleSettingsSave); //load settings and stylesettings gui.loadFromFile("settings.xml"); style_gui.loadFromFile("stylesettings.xml"); //dimensions for final output //after settings are loaded from file ofSetWindowShape(outputwidth, outputheight); outputRect = ofRectangle(0,0,outputwidth, outputheight); //set positions for style and normal gui style_gui.setPosition(ofGetWidth() - 2*style_gui.getWidth() - 20, 10); gui.setPosition(ofGetWidth() - gui.getWidth() - 10, 10); //some more listeners for the gui stroke_to_obstacle.addListener(this, &gFrameApp::onStrokeToObstacleChanged); vertical_obstacle.addListener(this, &gFrameApp::onVerticalObstacleChanged); //flowfield & gui obstacle.load("obstacle/obstacle_fullheight.jpg"); mapping_aid.load("obstacle/obstacle_mapping_aid.jpg"); simple_flow.setup(outputRect.width/2, outputRect.height/2, flow_scale); flowGuiSetup(); flow_gui.loadFromFile("demo_4.xml"); ofAddListener(flow_gui.loadPressedE, this, &gFrameApp::onFlowSettingsReload); ofAddListener(flow_gui.savePressedE, this, &gFrameApp::onFlowSettingsSave); simple_flow.use_seperate_fluid_color.addListener(this, &gFrameApp::onSepFluidColorChanged); simple_flow_2.setup(outputRect.width/2, outputRect.height/2, flow_scale); flow2GuiSetup(); flow2_gui.loadFromFile("demo_4_back.xml"); ofAddListener(flow2_gui.loadPressedE, this, &gFrameApp::onFlow2SettingsReload); ofAddListener(flow2_gui.savePressedE, this, &gFrameApp::onFlow2SettingsSave); fluidColor = localBrushColor; //need to call this here, otherwise would get a BAD ACCESS FAULT gui.draw(); style_gui.draw(); //Syphon stuff syphonMainOut.setName("gFrame Main Out"); //TUIO setup tuioClient.start(tuioPort); ofAddListener(tuioClient.cursorAdded,this,&gFrameApp::tuioAdded); ofAddListener(tuioClient.cursorUpdated,this,&gFrameApp::tuioUpdated); ofAddListener(tuioClient.cursorRemoved,this,&gFrameApp::tuioRemoved); //OSC receiver.setup(local_osc_port); // NETWORK //network.setup(host_port, remote_ip, remote_port); //stroke_list.setupSync(&network); canvasFBO.allocate(outputRect.width, outputRect.height, GL_RGBA, 8); canvasFBO.begin(); ofClear(0); canvasFBO.end(); obstacleFBO.allocate(outputRect.width, outputRect.height, GL_RGBA, 8); obstacleFBO.begin(); ofClear(0); obstacleFBO.end(); // initialize finger positions for(ofVec2f finger : finger_positions){ finger = ofVec2f(0,0); } render_mapping_aid = false; //load the LUTfile loadLUTFile("LUT/lutxml.xml"); //shader for converting the obstaclefbo to bw image for the obstacle buffer setupConvert2BWShader(); vector<ofVideoDevice> devices = vidGrabber.listDevices(); for(int i = 0; i < devices.size(); i++){ if(devices[i].bAvailable){ ofLogNotice() << devices[i].id << ": " << devices[i].deviceName; }else{ ofLogNotice() << devices[i].id << ": " << devices[i].deviceName << " - unavailable "; } } vidGrabber.setDeviceID(0); vidGrabber.setDesiredFrameRate(30); vidGrabber.initGrabber(320, 240); videoInverted.allocate(320, 240, OF_PIXELS_RGB); videoTexture.allocate(videoInverted); }
void testApp::pickNewSet(){ //chance to change the number of videos if(ofRandomuf() > .8){ numVideos = (rand() % maxNumVideos) + 1; } numVideos =4 ; //select 4 new videos, ones that haven't been seen for a while int currentSelections[numVideos]; for(int i = 0; i < numVideos; i++){ currentSelections[i] = -1; } for(int v = 0; v < numVideos; v++){ int validIndex = 0; int tries = 0; do { validIndex = rand() % options.size(); bool alreadySelected = false; for(int s = 0; s < v; s++){ if(currentSelections[s] == validIndex){ cout << "already selected " << s << endl; alreadySelected = true; } } if(!alreadySelected && options[validIndex]->loopsAgoPlayed > 1){ cout << "Accepting movie " << validIndex << " for " << options[validIndex]->file << endl; break; } } while (tries++ < 100); cout << "current file is " << player[v]->currentFile << " new file is " << options[validIndex]->file << endl; currentSelections[v] = validIndex; player[v]->playFile(options[validIndex]->file); options[validIndex]->loopsAgoPlayed = 0; } //update pick count for(int i = 0; i < options.size(); i++){ options[i]->loopsAgoPlayed++; } for(int i = 0; i < numVideos; i++){ options[ currentSelections[i] ]->loopsAgoPlayed = 0; } //calculate offset times float currentTime = ofGetElapsedTimef(); float maxBuildupTime = 0; for(int i = 0; i < numVideos; i++){ if(options[ currentSelections[i] ]->dropPoint > maxBuildupTime){ maxBuildupTime = options[ currentSelections[i] ]->dropPoint; } } int maxIndex; float maxDropLength = 0; for(int i = 0; i < numVideos; i++){ player[i]->calculatedStartTime = currentTime + maxBuildupTime - options[ currentSelections[i] ]->dropPoint; float dropLength = player[i]->player->getDuration() - options[ currentSelections[i] ]->dropPoint; if(dropLength > maxDropLength){ maxIndex = i; maxDropLength = dropLength; } } //turn off sound for(int i = 0; i < numVideos; i++){ player[i]->player->setVolume(0); } player[maxIndex]->player->setVolume(1); vector<bool> usedgridspots; for(int i = 0; i < numVideos*numVideos; i++) { usedgridspots.push_back(false); } for(int i = 0; i < numVideos; i++){ int gridSpot; do{ gridSpot = rand() % usedgridspots.size(); } while(usedgridspots[gridSpot]); usedgridspots[gridSpot] = true; int x = gridSpot%numVideos; int y = gridSpot/numVideos; int width = 1.0*ofGetWidth()/numVideos; int height = 1.0*ofGetHeight()/numVideos; player[i]->setDrawRect( ofRectangle(x*width, y*height, width, height) ); } }
//----------------------------------------------------- void ofxSURFTracker::detect(unsigned char *pix, int inputWidth, int inputHeight) { /*** code adapted from http://docs.opencv.org/doc/tutorials/features2d/feature_homography/feature_homography.html ***/ if( inputWidth != inputImg.getWidth() || inputHeight != inputImg.getHeight()) { // this should only happen once inputImg.clear(); inputImg.allocate(inputWidth, inputHeight); cout << "ofxSURFTracker : re-allocated the input image."<<endl; } // create the cvImage from the ofImage inputImg.setFromPixels(pix, inputWidth, inputHeight); inputImg.setROI( ofRectangle((inputWidth-width)/2, (inputHeight-height)/2, width, height ) ); // take out the piece that we want to use. croppedImg.setFromPixels(inputImg.getRoiPixels(), width, height); // make it into a trackable grayscale image trackImg = croppedImg; // do some fancy contrast stuff if(bContrast) { trackImg.contrastStretch(); } // set up the feature detector detector = SurfFeatureDetector(hessianThreshold, octaves, octaveLayers, bUpright); // clear existing keypoints from previous frame keypoints_scene.clear(); // get the Mat to do the feature detection on Mat trackMat = cvarrToMat(trackImg.getCvImage()); detector.detect( trackMat, keypoints_scene); // Calculate descriptors (feature vectors) extractor.compute( trackMat, keypoints_scene, descriptors_scene ); // Matching descriptor vectors using FLANN matcher vector< DMatch > matches; if(!descriptors_object.empty() && !descriptors_scene.empty() ) { flannMatcher.match( descriptors_object, descriptors_scene, matches); } // Quick calculation of max and min distances between keypoints double max_dist = 0; double min_dist = 100; for( int i = 0; i < matches.size(); i++ ) { double dist = matches[i].distance; if( dist < min_dist ) min_dist = dist; if( dist > max_dist ) max_dist = dist; } // Filter matches upon quality : distance is between 0 and 1, lower is better good_matches.clear(); for( int i = 0; i < matches.size(); i++ ) { if(matches[i].distance < 3 * min_dist && matches[i].distance < distanceThreshold) { good_matches.push_back( matches[i]); } } // find the homography // transform the bounding box for this scene vector <Point2f> scene_pts; vector <Point2f> object_pts; object_transformed.clear(); if(good_matches.size() > minMatches) { for( int i = 0; i < good_matches.size(); i++ ) { //-- Get the keypoints from the good matches object_pts.push_back( keypoints_object[ good_matches[i].queryIdx ].pt ); scene_pts.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt ); } if( scene_pts.size() >5 && object_pts.size() > 5) { homography = findHomography( object_pts, scene_pts, CV_RANSAC); perspectiveTransform( object, object_transformed, homography); } // being here means we have found a decent match objectLifeTime += 0.05; } else { // we haven't found a decent match objectLifeTime -= 0.05; } if(objectLifeTime > 1) { objectLifeTime = 1; } else if( objectLifeTime < 0) { objectLifeTime = 0; } }
void StCvOpSparkle::draw(){ ofxUIIntSlider *gskip = (ofxUIIntSlider *)gui->getWidget("SKIP"); int skip = gskip->getValue(); ofxUIIntSlider *gmax = (ofxUIIntSlider *)gui->getWidget("MAX"); int max = gmax->getValue(); ofxUISlider *gthresh = (ofxUISlider *)gui->getWidget("THRESH"); float thresh = gthresh->getValue(); ofxUISlider *gradius = (ofxUISlider *)gui->getWidget("RADIUS"); float radius = gradius->getValue(); ofxUISlider *gfriction = (ofxUISlider *)gui->getWidget("FRICTION"); float friction = gfriction->getValue(); ofxUISlider *gaccel = (ofxUISlider *)gui->getWidget("ACCEL"); float accel = gaccel->getValue(); ofxUISlider *ghue = (ofxUISlider *)gui->getWidget("HUE"); float hue = ghue->getValue(); ofxUISlider *gsat = (ofxUISlider *)gui->getWidget("SAT"); float sat = gsat->getValue(); ofxUISlider *gbr = (ofxUISlider *)gui->getWidget("BR"); float br = gbr->getValue(); ofPixelsRef pix = ((ofApp*)ofGetAppPtr())->blackmagic->colorPixels; int camWidth = SCREEN_WIDTH; int camHeight = SCREEN_HEIGHT; pix.resize(camWidth, camHeight); app->drawFbo->fbo.begin(); app->drawFbo->blendMode = 1; ofScale(1.0 / fxRatio, 1.0 / fxRatio); post->begin(); ofScale(fxRatio, fxRatio); ofDisableAlphaBlending(); ofClear(0,0,0); ofTranslate(0, -app->drawFbo->top); if (flow.getWidth() > 0) { ofVec2f scale = ofVec2f(SCREEN_WIDTH / float(flow.getWidth()), SCREEN_HEIGHT / float(flow.getHeight())); ofPushMatrix(); ofScale(scale.x, scale.y); int controlMax = powf(app->oscControl->controlVal[4] * 0.125, 1.5); for (int i = 0; i < controlMax; i++) { int x = ofRandom(flow.getWidth()-skip); int y = ofRandom(flow.getHeight()-skip); ofRectangle region = ofRectangle(x, y, skip, skip); ofVec2f average = flow.getAverageFlowInRegion(region); if (average.length() > thresh) { average = ofVec2f(0, 0); } if (abs(average.x) + abs(average.y) > 0.5) { ofColor col; col.setHsb(ofRandom(255), sat * 255, br * 255); NoteParticle *p = new NoteParticle(); p->setup(ofVec2f(x + ofRandom(skip), y + ofRandom(skip)), ofVec2f(average.x * accel, average.y * accel), col); p->radius = (abs(average.x) + abs(average.y)) * radius; p->friction = friction; if (abs(p->radius) > skip) { p->radius = skip; } particles.push_back(p); while (particles.size() > controlMax) { delete particles[0]; particles.pop_front(); } } } ofEnableBlendMode(OF_BLENDMODE_ADD); for (int i = 0; i < particles.size(); i++) { // ofSetColor(particles[i]->color); float controlHue; controlHue = ofMap(app->oscControl->controlVal[5], 0, 127, 0, 0.6); ofColor col; col.setHsb(controlHue * 255, sat * 255, br * 255); ofSetColor(col); ofSetRectMode(OF_RECTMODE_CENTER); ofPushMatrix(); ofTranslate(particles[i]->position); ofRotateZ(particles[i]->rot.z); img[particles[i]->imgNum].draw(0, 0, 0, particles[i]->radius * radius, particles[i]->radius * radius); ofPopMatrix(); ofSetRectMode(OF_RECTMODE_CORNER); } ofDisableBlendMode(); ofPopMatrix(); } post->end(); app->drawFbo->fbo.end(); gui->setVisible(getSharedData().guiVisible); }
//-------------------------------------------------------------- void SimpleOpenCVScene::update() { BaseScene::update( ) ; depthCameraManager->update( ); depthCameraManager->calculateCVOperations() ; //Set the values to very high so it's overriden easily boundingBox = ofRectangle( 40000 , 40000 , 0 , 0 ) ; ofxCvContourFinder * c = &depthCameraManager->contourFinder ; if ( c->nBlobs > 0 ) { paths.clear() ; //c++ 11 has some cool new looping tricks like the auto iterator for( auto blob = c->blobs.begin() ; blob != c->blobs.end() ; blob++ ) { //Polyline are good for smoothing / resampling CV blobs ofPolyline line ; float nPoint = 0.0f ; float nPointInc = 1.0f / ( float ) (*blob).pts.size() ; for ( auto pt = (*blob).pts.begin() ; pt != (*blob).pts.end() ; pt++ ) { if ( nPoint < completion ) { //Transform the CV points from pixel space to screenspace line.addVertex( depthCameraManager->cvPointToScreen( (*pt) , ofGetWidth() , ofGetHeight() ) ); nPoint += nPointInc ; } } line = line.getSmoothed( outlineSmoothing ) ; //Paths are good for storing more complex shapes , colors, and fills int index = paths.size() ; paths.push_back( ofPath() ) ; if ( line.getVertices().size() > 0 ) { paths[ index ].moveTo( line.getVertices()[0] ) ; for ( auto pt = line.getVertices().begin() ; pt != line.getVertices().end() ; pt++ ) { paths[ index ].lineTo( (*pt) ) ; } } paths[ index ].close() ; //if ( completion == 1.0f ) paths[ index ].setFilled( true ) ; float normalized = (float)index / ( (float)( c->nBlobs ) ) ; ofColor pathFill = ofColor::fromHsb( normalized * 255.0f , 255 , 255 ) ; paths[ index ].setFillColor( pathFill ) ; ofRectangle bb = line.getBoundingBox() ; if ( bb.x < boundingBox.x ) boundingBox.x = bb.x ; if ( bb.y > boundingBox.y ) boundingBox.y = bb.y ; if ( bb.width > boundingBox.width ) boundingBox.width = bb.width ; if ( bb.height > boundingBox.height ) boundingBox.height = bb.height ; } } }