Skip to content

Instantly share code, notes, and snippets.

@prisonerjohn
Created November 21, 2019 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prisonerjohn/730de0153eb6cc963d34f0a1abfc6546 to your computer and use it in GitHub Desktop.
Save prisonerjohn/730de0153eb6cc963d34f0a1abfc6546 to your computer and use it in GitHub Desktop.
OF Metaballs
#include "ofApp.h"
#include <glm/gtx/fast_square_root.hpp>
void ofApp::setup()
{
for (int i = 0; i < 10; i++)
{
blobs.push_back(Blob(ofRandomWidth(), ofRandomHeight()));
}
canvas.allocate(ofGetWidth(), ofGetHeight(), OF_IMAGE_GRAYSCALE);
}
void ofApp::update()
{
for (Blob& b : blobs)
{
b.update();
}
auto pixels = canvas.getPixels().getData();
for (int x = 0; x < ofGetWidth(); x++)
{
for (int y = 0; y < ofGetHeight(); y++)
{
int index = x + y * ofGetWidth();
float sum = 0;
for (Blob& b : blobs)
{
//float d = glm::distance(glm::vec2(x, y), b.pos);
//float d = glm::fastDistance(glm::vec2(x, y), b.pos);
glm::vec2 toPos = b.pos - glm::vec2(x, y);
float d = sqrtf(toPos.x * toPos.x + toPos.y * toPos.y);
sum += 10 * b.r / d;
}
pixels[index] = min(255.0f, sum);
}
}
canvas.update();
}
void ofApp::draw()
{
canvas.draw(0, 0);
ofDrawBitmapStringHighlight(ofToString(ofGetFrameRate(), 2), 10, 20);
}
#pragma once
#include "ofMain.h"
class Blob
{
public:
glm::vec2 pos;
float r;
glm::vec2 vel;
Blob(float x, float y)
{
pos = glm::vec2(x, y);
vel = glm::vec2(ofRandomf(), ofRandomf());
vel *= ofRandom(2, 5);
r = ofRandom(120, 400);
}
void update()
{
pos += vel;
if (pos.x > ofGetWidth() || pos.x < 0)
{
vel.x *= -1;
}
if (pos.y > ofGetHeight() || pos.y < 0)
{
vel.y *= -1;
}
}
};
class ofApp : public ofBaseApp
{
public:
void setup();
void update();
void draw();
std::vector<Blob> blobs;
ofImage canvas;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment