<commit_before>#include "App.h"

//--------------------------------------------------------------
void App::setup() {

    ofBackground(255);
    ofSetFrameRate(60);
    //ofSetVerticalSync(true);

    //initialise camera
	camWidth 		= CAM_WIDTH;	// try to grab at this size.
	camHeight 		= CAM_HEIGHT;

	//vidGrabber.listVideoDevices();
    vidGrabber.setVideoDeviceID(0); //0 is first, iSight is always last, so this is safe...
	vidGrabber.initGrabber(camWidth, camHeight);

    //now LUTs

    dir.allowExt("cube");
	dir.listDir("LUTs/");
	dir.sort();
	if (dir.size()>0) {
		dirLoadIndex=0;
		loadLUT(dir.getPath(dirLoadIndex));
		doLUT = true;
	}else{
		doLUT = false;
	}
	doLUT = false; // roxlu (drops fps to 11)

	lutImg.allocate(camWidth, camHeight, OF_IMAGE_COLOR);

    //now fonts
    AppAssets::inst()->appFont.loadFont("fonts/Helvetica.ttf", 12);

    // add all the scenes
    scenes.push_back(&cellSC);
    scenes.push_back(&drawnSC);
    scenes.push_back(&textureSC);
    scenes.push_back(&spotsSC);

    // setup the scenes
    for(vector<BaseScene*>::iterator it = scenes.begin(); it != scenes.end(); ++it) {
        (*it)->setup();
        (*it)->exitScene();

    }

    // start with the frist scene
    sceneIndex   = SCENE_TEXTURE;
    changeScene(sceneIndex);

	twitter.init();
	// fx.setup(CUBE_SCREEN_WIDTH, CUBE_SCREEN_HEIGHT);
    fx_duration = 5.5; // sec
	fx.setup(ofGetWidth(), ofGetHeight()); //like this for now....
	twitter.getSimulator().setEffects(fx);
	command_timeout = ofGetElapsedTimef() + fx_duration;
}

//--------------------------------------------------------------
void App::update() {
	float now = ofGetElapsedTimef();
	if(now >= command_timeout) {
		if(twitter.hasNewCommands() && twitter.getNextCommand(command)) {
			string switch_scene;
			if(command.mustSwitchScene(switch_scene)) {
				if(switch_scene == "cell") {
					currentScene = &cellSC;
				}
				else if(switch_scene == "drawn") {
					currentScene = &drawnSC;
				}
				else if(switch_scene == "texture") {
					currentScene = &textureSC;
				}
				else if(switch_scene == "spots") {
					currentScene = &spotsSC;
				}
			}
			currentScene->handleCommands(command, fx);
		}
		else {
			fx.reset();
		}
		command_timeout = now + fx_duration;
	}

	fx.update();

    twitter.update();
	vidGrabber.update();

	if (vidGrabber.isFrameNew()){
        //new frame fun here....

        if (doLUT) {
           // applyLUT(vidGrabber.getPixelsRef());
        }
	}

    // later maybe just update the scene that needs to be rendered
    for(vector<BaseScene*>::iterator it = scenes.begin(); it != scenes.end(); ++it) {
        (*it)->update();
    }
}

//--------------------------------------------------------------
void App::draw() {
	fx.beginGrabPixels();

    //ofBackgroundGradient(ofColor(40, 60, 70), ofColor(10,10,10));

    if(bExportPDF) {
        ofBeginSaveScreenAsPDF("exports/"+ofToString(ofGetUnixTime())+".pdf");
    }

    // we only want to draw the current screen
    // later we will have a transition from
    // one scene to the next
    if(currentScene != NULL) {
        ofSetColor(255);
        currentScene->draw();
    }

	fx.endGrabPixels();
    fx.draw();

    if(doLUT){
        lutImg.draw(CUBE_SCREEN_WIDTH,0,CAMERA_PROJECTION_SCREEN_WIDTH, CAMERA_PROJECTION_SCREEN_HEIGHT);
//		lutImg.draw(lutPos.x, lutPos.y);
//		ofRect(thumbPos.x-3, thumbPos.y-3, 166, 126);
//		vidGrabber.draw(thumbPos.x, thumbPos.y, 160, 120);
//
//		ofDrawBitmapString(dir.getName(dirLoadIndex), lutPos.x, -lutPos.y+50);
//
//		ofDrawBitmapString("Use the up and down arrows of your keyboard \nto go through the different filters", lutPos.x, -lutPos.y+100);

	}else {
        vidGrabber.draw(CUBE_SCREEN_WIDTH,0,CAMERA_PROJECTION_SCREEN_WIDTH, CAMERA_PROJECTION_SCREEN_HEIGHT); //stick the camera up on screen....
	}

    if(bExportPDF) {
        bExportPDF = false;
        ofEndSaveScreenAsPDF();
    }

	if(twitter.getSimulator().take_screenshot) {
		rtt::Tweet tweet;
		tweet.setScreenName("roxlutest");
		bool grab = 1; // 0 = screen, 1 = webcam

		if(grab == 0) {
			ofImage img;
			img.grabScreen(0,0,ofGetWidth(), ofGetHeight());
			twitter.getUploader().uploadScreenshot(
				 (unsigned char*)img.getPixels()
				,img.getWidth()
				,img.getHeight()
				,tweet
			);
		}
		else if(grab == 1) {
			twitter.getUploader().uploadScreenshot(
				 (unsigned char*)vidGrabber.getPixels()
				,vidGrabber.getWidth()
				,vidGrabber.getHeight()
				,tweet
			);
		}
		twitter.getSimulator().take_screenshot = false;
	}

    // draw some stats about the app...
    ofEnableAlphaBlending();
    ofFill();
    ofSetColor(255, 130);
    ofRect(0, ofGetHeight()-60, 255, 60);
    ofSetColor(0);
    string info;
    info += ofToString(ofGetFrameRate(), 0)+" fps\n";
    if(currentScene) info += "scene "+currentScene->name+"\n";
    ofDrawBitmapString(info, 10, ofGetHeight()-40);

}

//--------------------------------------------------------------
void App::changeScene(int scene) {

    BaseScene * lastScene = scenes[sceneIndex];
    lastScene->exitScene();

    sceneIndex = scene;
    currentScene = scenes[scene];
    currentScene->enterScene();

}

//--------------------------------------------------------------
void App::keyPressed(int key) {

    // scene changing
    if(key == OF_KEY_RIGHT) sceneIndex++;
    if(key == OF_KEY_LEFT)  sceneIndex--;
    sceneIndex %= (int)scenes.size();
    if(sceneIndex < 0) sceneIndex = scenes.size()-1;

    changeScene(sceneIndex);

    if(currentScene!=NULL)currentScene->keyPressed(key);

    // for exporting a screen grab
    if(key == 'E') {
        ofSaveScreen("exports/"+ofToString(ofGetUnixTime())+".png");
    }
    if(key == 'P') {
        bExportPDF = true;
    }

    // fullscreen or not
    if(key == 'f') ofToggleFullscreen();

    switch (key) { //JGL should clean this up
		case 'L':
			doLUT^=true;
			break;
		case OF_KEY_UP:
			dirLoadIndex++;
			if (dirLoadIndex>=dir.size()) {
				dirLoadIndex=0;
			}
			loadLUT(dir.getPath(dirLoadIndex));

			break;
		case OF_KEY_DOWN:
			dirLoadIndex--;
			if (dirLoadIndex<0) {
				dirLoadIndex=dir.size()-1;
			}
			loadLUT(dir.getPath(dirLoadIndex));
			break;
		default:
			break;
	}
}

//--------------------------------------------------------------
void App::keyReleased(int key){
    if(currentScene!=NULL)currentScene->keyReleased(key);
}

//--------------------------------------------------------------
void App::mouseMoved(int x, int y ){
    if(currentScene!=NULL)currentScene->mouseMoved(x, y);
}

//--------------------------------------------------------------
void App::mouseDragged(int x, int y, int button){
    if(currentScene!=NULL)currentScene->mouseDragged(x, y, button);

}

//--------------------------------------------------------------
void App::mousePressed(int x, int y, int button){
    if(currentScene!=NULL)currentScene->mousePressed(x, y, button);
}

//--------------------------------------------------------------
void App::mouseReleased(int x, int y, int button){
    if(currentScene!=NULL)currentScene->mouseReleased(x, y, button);
}

//--------------------------------------------------------------
void App::windowResized(int w, int h){

}

//--------------------------------------------------------------
void App::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void App::dragEvent(ofDragInfo dragInfo){

}

//--------------------------------------------------------------
void App::loadLUT(string path){
    LUTloaded=false;

    ofFile file(path);
    string line;
    for(int i = 0; i < 5; i++) {
     getline(file, line);
     ofLog() << "Skipped line: " << line;
    }
    for(int z=0; z<32; z++){
     for(int y=0; y<32; y++){
         for(int x=0; x<32; x++){
             ofVec3f cur;
             file >> cur.x >> cur.y >> cur.z;
             lut[x][y][z] = cur;
         }
     }
    }

    LUTloaded = true;
}
//--------------------------------------------------------------
void App::applyLUT(ofPixelsRef pix){
    if (LUTloaded) {

     for(int y = 0; y < pix.getHeight(); y++){
         for(int x = 0; x < pix.getWidth(); x++){

             ofColor color = pix.getColor(x, y);

             int lutPos [3];
             for (int m=0; m<3; m++) {
                 lutPos[m] = color[m] / 8;
                 if (lutPos[m]==31) {
                     lutPos[m]=30;
                 }
             }

             ofVec3f start = lut[lutPos[0]][lutPos[1]][lutPos[2]];
             ofVec3f end = lut[lutPos[0]+1][lutPos[1]+1][lutPos[2]+1];

             for (int k=0; k<3; k++) {
                 float amount = (color[k] % 8) / 8.0f;
                 color[k]= (start[k] + amount * (end[k] - start[k])) * 255;
             }

             lutImg.setColor(x, y, color);

         }
     }

     lutImg.update();
    }
}<commit_msg>Cleaning App.cpp<commit_after>#include "App.h"

//--------------------------------------------------------------
void App::setup() {

    ofBackground(255);
    ofSetFrameRate(60);
    //ofSetVerticalSync(true);

    //initialise camera
	camWidth 		= CAM_WIDTH;	// try to grab at this size.
	camHeight 		= CAM_HEIGHT;

	//vidGrabber.listVideoDevices();
    vidGrabber.setVideoDeviceID(0); //0 is first, iSight is always last, so this is safe...
	vidGrabber.initGrabber(camWidth, camHeight);

    //now LUTs

    dir.allowExt("cube");
	dir.listDir("LUTs/");
	dir.sort();
	if (dir.size()>0) {
		dirLoadIndex=0;
		loadLUT(dir.getPath(dirLoadIndex));
		doLUT = true;
	}else{
		doLUT = false;
	}
	doLUT = false; // roxlu (drops fps to 11)

	lutImg.allocate(camWidth, camHeight, OF_IMAGE_COLOR);

    //now fonts
    AppAssets::inst()->appFont.loadFont("fonts/Helvetica.ttf", 12);

    // add all the scenes
    scenes.push_back(&cellSC);
    scenes.push_back(&drawnSC);
    scenes.push_back(&textureSC);
    scenes.push_back(&spotsSC);

    // setup the scenes
    for(vector<BaseScene*>::iterator it = scenes.begin(); it != scenes.end(); ++it) {
        (*it)->setup();
        (*it)->exitScene();

    }

    // start with the frist scene
    sceneIndex   = SCENE_TEXTURE;
    changeScene(sceneIndex);

	twitter.init();
	// fx.setup(CUBE_SCREEN_WIDTH, CUBE_SCREEN_HEIGHT);
    fx_duration = 5.5; // sec
	fx.setup(ofGetWidth(), ofGetHeight()); //like this for now....
	twitter.getSimulator().setEffects(fx);
	command_timeout = ofGetElapsedTimef() + fx_duration;
}

//--------------------------------------------------------------
void App::update() {
	float now = ofGetElapsedTimef();
	if(now >= command_timeout) {
		if(twitter.hasNewCommands() && twitter.getNextCommand(command)) {
			string switch_scene;
			if(command.mustSwitchScene(switch_scene)) {
				if(switch_scene == "cell") {
					currentScene = &cellSC;
				}
				else if(switch_scene == "drawn") {
					currentScene = &drawnSC;
				}
				else if(switch_scene == "texture") {
					currentScene = &textureSC;
				}
				else if(switch_scene == "spots") {
					currentScene = &spotsSC;
				}
			}
			currentScene->handleCommands(command, fx);
		}
		else {
			fx.reset();
		}
		command_timeout = now + fx_duration;
	}

	fx.update();
    twitter.update();
	vidGrabber.update();

	if (vidGrabber.isFrameNew()){
        //new frame fun here....

        if (doLUT) {
           // applyLUT(vidGrabber.getPixelsRef());
        }
	}

    // later maybe just update the scene that needs to be rendered
    for(vector<BaseScene*>::iterator it = scenes.begin(); it != scenes.end(); ++it) {
        (*it)->update();
    }
}

//--------------------------------------------------------------
void App::draw() {
	fx.beginGrabPixels();

    //ofBackgroundGradient(ofColor(40, 60, 70), ofColor(10,10,10));

    if(bExportPDF) {
        ofBeginSaveScreenAsPDF("exports/"+ofToString(ofGetUnixTime())+".pdf");
    }

    // we only want to draw the current screen
    // later we will have a transition from
    // one scene to the next
    if(currentScene != NULL) {
        ofSetColor(255);
        currentScene->draw();
    }

	fx.endGrabPixels();
    fx.draw();

    if(doLUT){
        lutImg.draw(CUBE_SCREEN_WIDTH,0,CAMERA_PROJECTION_SCREEN_WIDTH, CAMERA_PROJECTION_SCREEN_HEIGHT);
//		lutImg.draw(lutPos.x, lutPos.y);
//		ofRect(thumbPos.x-3, thumbPos.y-3, 166, 126);
//		vidGrabber.draw(thumbPos.x, thumbPos.y, 160, 120);
//
//		ofDrawBitmapString(dir.getName(dirLoadIndex), lutPos.x, -lutPos.y+50);
//
//		ofDrawBitmapString("Use the up and down arrows of your keyboard \nto go through the different filters", lutPos.x, -lutPos.y+100);

	}else {
        vidGrabber.draw(CUBE_SCREEN_WIDTH,0,CAMERA_PROJECTION_SCREEN_WIDTH, CAMERA_PROJECTION_SCREEN_HEIGHT); //stick the camera up on screen....
	}

    if(bExportPDF) {
        bExportPDF = false;
        ofEndSaveScreenAsPDF();
    }

	if(twitter.getSimulator().take_screenshot) {
		rtt::Tweet tweet;
		tweet.setScreenName("roxlutest");
		bool grab = 1; // 0 = screen, 1 = webcam

		if(grab == 0) {
			ofImage img;
			img.grabScreen(0,0,ofGetWidth(), ofGetHeight());
			twitter.getUploader().uploadScreenshot(
				 (unsigned char*)img.getPixels()
				,img.getWidth()
				,img.getHeight()
				,tweet
			);
		}
		else if(grab == 1) {
			twitter.getUploader().uploadScreenshot(
				 (unsigned char*)vidGrabber.getPixels()
				,vidGrabber.getWidth()
				,vidGrabber.getHeight()
				,tweet
			);
		}
		twitter.getSimulator().take_screenshot = false;
	}

    // draw some stats about the app...
    ofEnableAlphaBlending();
    ofFill();
    ofSetColor(255, 130);
    ofRect(0, ofGetHeight()-60, 255, 60);
    ofSetColor(0);
    string info;
    info += ofToString(ofGetFrameRate(), 0)+" fps\n";
    if(currentScene) info += "scene "+currentScene->name+"\n";
    ofDrawBitmapString(info, 10, ofGetHeight()-40);

}

//--------------------------------------------------------------
void App::changeScene(int scene) {

    BaseScene * lastScene = scenes[sceneIndex];
    lastScene->exitScene();

    sceneIndex = scene;
    currentScene = scenes[scene];
    currentScene->enterScene();

}

//--------------------------------------------------------------
void App::keyPressed(int key) {

    // scene changing
    if(key == OF_KEY_RIGHT) sceneIndex++;
    if(key == OF_KEY_LEFT)  sceneIndex--;
    sceneIndex %= (int)scenes.size();
    if(sceneIndex < 0) sceneIndex = scenes.size()-1;

    changeScene(sceneIndex);

    if(currentScene!=NULL)currentScene->keyPressed(key);

    // for exporting a screen grab
    if(key == 'E') {
        ofSaveScreen("exports/"+ofToString(ofGetUnixTime())+".png");
    }
    if(key == 'P') {
        bExportPDF = true;
    }

    // fullscreen or not
    if(key == 'f') ofToggleFullscreen();

    switch (key) { //JGL should clean this up
		case 'L':
			doLUT^=true;
			break;
		case OF_KEY_UP:
			dirLoadIndex++;
			if (dirLoadIndex>=dir.size()) {
				dirLoadIndex=0;
			}
			loadLUT(dir.getPath(dirLoadIndex));

			break;
		case OF_KEY_DOWN:
			dirLoadIndex--;
			if (dirLoadIndex<0) {
				dirLoadIndex=dir.size()-1;
			}
			loadLUT(dir.getPath(dirLoadIndex));
			break;
		default:
			break;
	}
}

//--------------------------------------------------------------
void App::keyReleased(int key){
    if(currentScene!=NULL)currentScene->keyReleased(key);
}

//--------------------------------------------------------------
void App::mouseMoved(int x, int y ){
    if(currentScene!=NULL)currentScene->mouseMoved(x, y);
}

//--------------------------------------------------------------
void App::mouseDragged(int x, int y, int button){
    if(currentScene!=NULL)currentScene->mouseDragged(x, y, button);

}

//--------------------------------------------------------------
void App::mousePressed(int x, int y, int button){
    if(currentScene!=NULL)currentScene->mousePressed(x, y, button);
}

//--------------------------------------------------------------
void App::mouseReleased(int x, int y, int button){
    if(currentScene!=NULL)currentScene->mouseReleased(x, y, button);
}

//--------------------------------------------------------------
void App::windowResized(int w, int h){

}

//--------------------------------------------------------------
void App::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void App::dragEvent(ofDragInfo dragInfo){

}

//--------------------------------------------------------------
void App::loadLUT(string path){
    LUTloaded=false;

    ofFile file(path);
    string line;
    for(int i = 0; i < 5; i++) {
     getline(file, line);
     ofLog() << "Skipped line: " << line;
    }
    for(int z=0; z<32; z++){
     for(int y=0; y<32; y++){
         for(int x=0; x<32; x++){
             ofVec3f cur;
             file >> cur.x >> cur.y >> cur.z;
             lut[x][y][z] = cur;
         }
     }
    }

    LUTloaded = true;
}
//--------------------------------------------------------------
void App::applyLUT(ofPixelsRef pix){
    if (LUTloaded) {

     for(int y = 0; y < pix.getHeight(); y++){
         for(int x = 0; x < pix.getWidth(); x++){

             ofColor color = pix.getColor(x, y);

             int lutPos [3];
             for (int m=0; m<3; m++) {
                 lutPos[m] = color[m] / 8;
                 if (lutPos[m]==31) {
                     lutPos[m]=30;
                 }
             }

             ofVec3f start = lut[lutPos[0]][lutPos[1]][lutPos[2]];
             ofVec3f end = lut[lutPos[0]+1][lutPos[1]+1][lutPos[2]+1];

             for (int k=0; k<3; k++) {
                 float amount = (color[k] % 8) / 8.0f;
                 color[k]= (start[k] + amount * (end[k] - start[k])) * 255;
             }

             lutImg.setColor(x, y, color);

         }
     }

     lutImg.update();
    }
}<|endoftext|>


<commit_before>// MathLib.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <unittest.h>

int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
	run_tests();

	return 0;
}
<commit_msg>Test change to test both branch functionality and approval process<commit_after>// MathLib.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <unittest.h>

int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
	//test change
	run_tests();

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>*** empty log message ***<commit_after><|endoftext|>


<commit_before><commit_msg>main returns an int (standard conformance)<commit_after><|endoftext|>


<commit_before><commit_msg>dot 범위 벗어나는 버그 수<commit_after><|endoftext|>


<commit_before>#include "CompiledMaterialGenerator.h"
#include "../Effekseer/Effekseer/Material/Effekseer.MaterialCompiler.h"
#include "../EffekseerRendererCommon/EffekseerRenderer.ShaderLoader.h"
#include <fstream>

typedef Effekseer::MaterialCompiler*(EFK_STDCALL* CreateCompilerFunc)();

CompiledMaterialGenerator::CompiledMaterialGenerator() {}

CompiledMaterialGenerator::~CompiledMaterialGenerator() {}

bool CompiledMaterialGenerator::Initialize(const char* directory)
{

	std::map<Effekseer::CompiledMaterialPlatformType, std::string> names;

	names[Effekseer::CompiledMaterialPlatformType::DirectX9] = "DX9";
	names[Effekseer::CompiledMaterialPlatformType::DirectX11] = "DX11";
	names[Effekseer::CompiledMaterialPlatformType::DirectX12] = "DX12";
	names[Effekseer::CompiledMaterialPlatformType::Metal] = "MTL";
	names[Effekseer::CompiledMaterialPlatformType::Vulkan] = "VK";
	names[Effekseer::CompiledMaterialPlatformType::OpenGL] = "GL";
	names[Effekseer::CompiledMaterialPlatformType::Switch] = "Switch";
	names[Effekseer::CompiledMaterialPlatformType::PS4] = "PS4";

	for (auto& name : names)
	{
		std::string path = directory;

#ifdef _WIN32
		path += "EffekseerMaterialCompiler";
#elif defined(__APPLE__)
		path += "libEffekseerMaterialCompiler";
#else
		path += "libEffekseerMaterialCompiler";
#endif

		path += name.second;

#ifdef _WIN32
	#ifdef _DEBUG
		path += ".Debug.dll";
	#else
		path += ".dll";
	#endif
#elif defined(__APPLE__)
		path += ".dylib";
#else
		path += ".so";
#endif

		auto dll = std::make_shared<DynamicLinkLibrary>();
		if (dll->Load(path.c_str()))
		{
			dlls_[name.first] = dll;
		}
	}

	return true;
}

bool CompiledMaterialGenerator::Compile(const char* dstPath, const char* srcPath)
{
	auto load = [](const char* path) -> std::vector<uint8_t> {
		std::ifstream file(path, std::ios::binary);
		if (!file)
		{
			return std::vector<uint8_t>();
		}

		file.seekg(0, std::fstream::end);
		auto eofPos = file.tellg();
		file.clear();
		file.seekg(0, std::fstream::beg);
		auto begPos = file.tellg();
		auto size = eofPos - begPos;

		std::vector<uint8_t> data;
		data.resize(size);
		file.read((char*)data.data(), size);
		file.close();

		return data;
	};

	auto srcData = load(srcPath);
	auto dstData = load(dstPath);

	Effekseer::Material material;
	material.Load(srcData.data(), static_cast<int32_t>(srcData.size()));

	Effekseer::CompiledMaterial cm;

	if (dstData.size() > 0)
	{
		cm.Load(dstData.data(), static_cast<int32_t>(dstData.size()));
	}

	if (cm.GUID != material.GetGUID())
	{
		cm = Effekseer::CompiledMaterial();
	}

	for (auto dll : dlls_)
	{
		if (cm.GetHasValue(dll.first))
		{
			continue;
		}

		auto createCompiler = dll.second->GetProc<CreateCompilerFunc>("CreateCompiler");
		auto compiler = createCompiler();

		std::vector<uint8_t> vsStandardBinary;
		std::vector<uint8_t> psStandardBinary;
		std::vector<uint8_t> vsModelBinary;
		std::vector<uint8_t> psModelBinary;
		std::vector<uint8_t> vsRefractionStandardBinary;
		std::vector<uint8_t> psRefractionStandardBinary;
		std::vector<uint8_t> vsRefractionModelBinary;
		std::vector<uint8_t> psRefractionModelBinary;

		auto compile_and_store =
			[&compiler, &material](Effekseer::MaterialShaderType type, std::vector<uint8_t>& vs, std::vector<uint8_t>& ps) -> void {
			auto binary = compiler->Compile(&material);

			if (binary != nullptr)
			{

				vs.resize(binary->GetVertexShaderSize(type));
				memcpy(vs.data(), binary->GetVertexShaderData(type), binary->GetVertexShaderSize(type));

				ps.resize(binary->GetPixelShaderSize(type));
				memcpy(ps.data(), binary->GetPixelShaderData(type), binary->GetPixelShaderSize(type));
			}
		};

		compile_and_store(Effekseer::MaterialShaderType::Standard, vsStandardBinary, psStandardBinary);
		compile_and_store(Effekseer::MaterialShaderType::Model, vsModelBinary, psModelBinary);
		compile_and_store(Effekseer::MaterialShaderType::Refraction, vsRefractionStandardBinary, psRefractionStandardBinary);
		compile_and_store(Effekseer::MaterialShaderType::RefractionModel, vsRefractionModelBinary, psRefractionModelBinary);

		cm.UpdateData(vsStandardBinary,
					  psStandardBinary,
					  vsModelBinary,
					  psModelBinary,
					  vsRefractionStandardBinary,
					  psRefractionStandardBinary,
					  vsRefractionModelBinary,
					  psRefractionModelBinary,
					  dll.first);

		compiler->Release();
	}

	cm.Save(dstData, material.GetGUID(), srcData);

	std::ofstream file(dstPath, std::ios::out | std::ios::binary | std::ios::trunc);
	if (file.bad())
		return false;

	file.write((char*)dstData.data(), dstData.size());

	file.close();

	return true;
}
<commit_msg>fixed compile error<commit_after>#include "CompiledMaterialGenerator.h"
#include "../Effekseer/Effekseer/Material/Effekseer.MaterialCompiler.h"
#include <fstream>

typedef Effekseer::MaterialCompiler*(EFK_STDCALL* CreateCompilerFunc)();

CompiledMaterialGenerator::CompiledMaterialGenerator() {}

CompiledMaterialGenerator::~CompiledMaterialGenerator() {}

bool CompiledMaterialGenerator::Initialize(const char* directory)
{

	std::map<Effekseer::CompiledMaterialPlatformType, std::string> names;

	names[Effekseer::CompiledMaterialPlatformType::DirectX9] = "DX9";
	names[Effekseer::CompiledMaterialPlatformType::DirectX11] = "DX11";
	names[Effekseer::CompiledMaterialPlatformType::DirectX12] = "DX12";
	names[Effekseer::CompiledMaterialPlatformType::Metal] = "MTL";
	names[Effekseer::CompiledMaterialPlatformType::Vulkan] = "VK";
	names[Effekseer::CompiledMaterialPlatformType::OpenGL] = "GL";
	names[Effekseer::CompiledMaterialPlatformType::Switch] = "Switch";
	names[Effekseer::CompiledMaterialPlatformType::PS4] = "PS4";

	for (auto& name : names)
	{
		std::string path = directory;

#ifdef _WIN32
		path += "EffekseerMaterialCompiler";
#elif defined(__APPLE__)
		path += "libEffekseerMaterialCompiler";
#else
		path += "libEffekseerMaterialCompiler";
#endif

		path += name.second;

#ifdef _WIN32
	#ifdef _DEBUG
		path += ".Debug.dll";
	#else
		path += ".dll";
	#endif
#elif defined(__APPLE__)
		path += ".dylib";
#else
		path += ".so";
#endif

		auto dll = std::make_shared<DynamicLinkLibrary>();
		if (dll->Load(path.c_str()))
		{
			dlls_[name.first] = dll;
		}
	}

	return true;
}

bool CompiledMaterialGenerator::Compile(const char* dstPath, const char* srcPath)
{
	auto load = [](const char* path) -> std::vector<uint8_t> {
		std::ifstream file(path, std::ios::binary);
		if (!file)
		{
			return std::vector<uint8_t>();
		}

		file.seekg(0, std::fstream::end);
		auto eofPos = file.tellg();
		file.clear();
		file.seekg(0, std::fstream::beg);
		auto begPos = file.tellg();
		auto size = eofPos - begPos;

		std::vector<uint8_t> data;
		data.resize(size);
		file.read((char*)data.data(), size);
		file.close();

		return data;
	};

	auto srcData = load(srcPath);
	auto dstData = load(dstPath);

	Effekseer::Material material;
	material.Load(srcData.data(), static_cast<int32_t>(srcData.size()));

	Effekseer::CompiledMaterial cm;

	if (dstData.size() > 0)
	{
		cm.Load(dstData.data(), static_cast<int32_t>(dstData.size()));
	}

	if (cm.GUID != material.GetGUID())
	{
		cm = Effekseer::CompiledMaterial();
	}

	for (auto dll : dlls_)
	{
		if (cm.GetHasValue(dll.first))
		{
			continue;
		}

		auto createCompiler = dll.second->GetProc<CreateCompilerFunc>("CreateCompiler");
		auto compiler = createCompiler();

		std::vector<uint8_t> vsStandardBinary;
		std::vector<uint8_t> psStandardBinary;
		std::vector<uint8_t> vsModelBinary;
		std::vector<uint8_t> psModelBinary;
		std::vector<uint8_t> vsRefractionStandardBinary;
		std::vector<uint8_t> psRefractionStandardBinary;
		std::vector<uint8_t> vsRefractionModelBinary;
		std::vector<uint8_t> psRefractionModelBinary;

		auto compile_and_store =
			[&compiler, &material](Effekseer::MaterialShaderType type, std::vector<uint8_t>& vs, std::vector<uint8_t>& ps) -> void {
			auto binary = compiler->Compile(&material);

			if (binary != nullptr)
			{

				vs.resize(binary->GetVertexShaderSize(type));
				memcpy(vs.data(), binary->GetVertexShaderData(type), binary->GetVertexShaderSize(type));

				ps.resize(binary->GetPixelShaderSize(type));
				memcpy(ps.data(), binary->GetPixelShaderData(type), binary->GetPixelShaderSize(type));
			}
		};

		compile_and_store(Effekseer::MaterialShaderType::Standard, vsStandardBinary, psStandardBinary);
		compile_and_store(Effekseer::MaterialShaderType::Model, vsModelBinary, psModelBinary);
		compile_and_store(Effekseer::MaterialShaderType::Refraction, vsRefractionStandardBinary, psRefractionStandardBinary);
		compile_and_store(Effekseer::MaterialShaderType::RefractionModel, vsRefractionModelBinary, psRefractionModelBinary);

		cm.UpdateData(vsStandardBinary,
					  psStandardBinary,
					  vsModelBinary,
					  psModelBinary,
					  vsRefractionStandardBinary,
					  psRefractionStandardBinary,
					  vsRefractionModelBinary,
					  psRefractionModelBinary,
					  dll.first);

		compiler->Release();
	}

	cm.Save(dstData, material.GetGUID(), srcData);

	std::ofstream file(dstPath, std::ios::out | std::ios::binary | std::ios::trunc);
	if (file.bad())
		return false;

	file.write((char*)dstData.data(), dstData.size());

	file.close();

	return true;
}
<|endoftext|>


<commit_before>#include "draw.h"

void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue);
void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue);
void drawOnPixelBuffer();
void drawCircle(const int x, const int y, const int r, const int w, const float red, const float green, const float blue);

template<class T>
void print(T input)
{
	std::cout << input << std::endl;
}

template<class Vec>
class Vector2D
{
	Vec x_, y_;
};

class GeometricObjectInterface
{
public:
	virtual void draw() {}
};

template<class Shape>
class GeometricObject : public GeometricObjectInterface
{
public:
	void draw()
	{
		Shape object;
		object.draw();
	}
};

class Box
{
private:
	int o_x, o_y, o_r, o_w;

public:
	void setElements(int x, int y, int r, int w)
	{
		o_x = x;
		o_y = y;
		o_r = r;
		o_w = w;
	}

	void draw()
	{
		setElements(100, 100, 30, 3);

		drawLine((o_x - (o_r / 2)), (o_y - (o_r / 2)), (o_x - (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
		drawLine((o_x - (o_r / 2)), (o_y - (o_r / 2)), (o_x + (o_r / 2)), (o_y - (o_r / 2)), 1.0f, 0.0f, 0.0f);
		drawLine((o_x - (o_r / 2)), (o_y + (o_r / 2)), (o_x + (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
		drawLine((o_x + (o_r / 2)), (o_y - (o_r / 2)), (o_x + (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
	}

};

class Circle
{
private:
	int o_x, o_y, o_r, o_w;

public:
	void setElements(int x, int y, int r, int w)
	{
		o_x = x;
		o_y = y;
		o_r = r;
		o_w = w;
	}

	void draw()
	{
		setElements(300, 300, 30, 5);
		drawCircle(o_x, o_y, o_r, o_w, 0.0f, 0.0f, 1.0f);
	}
};

int main(void)
{
	GLFWwindow* window;
	/* Initialize the library */
	if (!glfwInit())
		return -1;

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow(width, height, "Week6 Templates", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	glfwMakeContextCurrent(window);
	glClearColor(1, 1, 1, 1); // while background

	//Question 1 Part
	print(1);
	print(2.345f);
	print("Hello World");

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{

		drawOnPixelBuffer();

		glDrawPixels(width, height, GL_RGB, GL_FLOAT, pixels);
		/* Swap front and back buffers */
		glfwSwapBuffers(window);
		/* Poll for and process events */
		glfwPollEvents();
	}

	glfwTerminate();

	delete[] pixels; // or you may reuse pixels array

	return 0;
}

void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue)
{
	pixels[(i + width* j) * 3 + 0] = red;
	pixels[(i + width* j) * 3 + 1] = green;
	pixels[(i + width* j) * 3 + 2] = blue;
}

void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue)
{
	if (i1 == i0) {
		for (int j = j0; j < j1; j++)
			drawPixel(i0, j, red, green, blue);
		return;
	}
	for (int i = i0; i <= i1; i++) {
		const int j = (j1 - j0)*(i - i0) / (i1 - i0) + j0;
		drawPixel(i, j, red, green, blue);
	}
}

void drawOnPixelBuffer()
{
	//std::memset(pixels, 1.0f, sizeof(float)*width*height * 3); // doesn't work
	std::fill_n(pixels, width*height * 3, 1.0f);	// white background

	//Question 3 Part
	std::vector<GeometricObjectInterface*> obj_list;
	obj_list.push_back(new GeometricObject<Circle>);
	obj_list.push_back(new GeometricObject<Box>);
	for (auto itr : obj_list)
		itr->draw();
}

//w is the width of the circle'outer shell
void drawCircle(const int x, const int y, const int r, const int w, const float red, const float green, const float blue)
{
	for (int a = 0; a < width; a++)
	{
		for (int b = 0; b < height; b++)
		{

			if (sqrt((x - a)*(x - a) + (y - b)*(y - b)) <= r)
			{
				if (sqrt((x - a)*(x - a) + (y - b)*(y - b)) >= r - w)
					drawPixel(a, b, red, green, blue);
			}
		}
	}
}
<commit_msg>Update main.cpp<commit_after>#include "draw.h"
#define ONE_OBJ 50
#define START_COORDINATES 100
using namespace std;

//predefinition of Methods
void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue);
void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue);
void drawOnPixelBuffer();
void drawCircle(const int x, const int y, const int r, const int w, const float red, const float green, const float blue);

template<class T>
void print(T input)
{
	cout << input << endl;
}

template<class Vec>
class Vector2D
{
	Vec x_, y_;
};

class GeometricObjectInterface
{
public:
	virtual void setElements(int x, int y, int r, int w) {}
	virtual void draw() {}
};

template<class Shape>
class GeometricObject : public GeometricObjectInterface
{
	Shape object;
public:

	void setElements(int x, int y, int r, int w)
	{
		object.setElements(x,y,r,w);
	}

	void draw()
	{
		object.draw();
	}
};

class Box
{
private:
	int o_x, o_y, o_r, o_w;

public:
	void setElements(int x, int y, int r, int w)
	{
		o_x = x;
		o_y = y;
		o_r = r;
		o_w = w;
	}

	void draw()
	{
		drawLine((o_x - (o_r / 2)), (o_y - (o_r / 2)), (o_x - (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
		drawLine((o_x - (o_r / 2)), (o_y - (o_r / 2)), (o_x + (o_r / 2)), (o_y - (o_r / 2)), 1.0f, 0.0f, 0.0f);
		drawLine((o_x - (o_r / 2)), (o_y + (o_r / 2)), (o_x + (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
		drawLine((o_x + (o_r / 2)), (o_y - (o_r / 2)), (o_x + (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
	}

};

class Circle
{
private:
	int o_x, o_y, o_r, o_w;

public:
	void setElements(int x, int y, int r, int w)
	{
		o_x = x;
		o_y = y;
		o_r = r;
		o_w = w;
	}

	void draw()
	{
		drawCircle(o_x, o_y, o_r, o_w, 0.0f, 0.0f, 1.0f);
	}
};

int main(void)
{
	GLFWwindow* window;
	/* Initialize the library */
	if (!glfwInit())
		return -1;

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow(width, height, "Week6 Templates", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	glfwMakeContextCurrent(window);
	glClearColor(1, 1, 1, 1); // while background

	//Question 1 Part
	print(1);
	print(2.345f);
	print("Hello World");

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{

		drawOnPixelBuffer();

		glDrawPixels(width, height, GL_RGB, GL_FLOAT, pixels);
		/* Swap front and back buffers */
		glfwSwapBuffers(window);
		/* Poll for and process events */
		glfwPollEvents();
	}

	glfwTerminate();

	delete[] pixels; // or you may reuse pixels array

	return 0;
}

void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue)
{
	pixels[(i + width* j) * 3 + 0] = red;
	pixels[(i + width* j) * 3 + 1] = green;
	pixels[(i + width* j) * 3 + 2] = blue;
}

void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue)
{
	if (i1 == i0) {
		for (int j = j0; j < j1; j++)
			drawPixel(i0, j, red, green, blue);
		return;
	}
	for (int i = i0; i <= i1; i++) {
		const int j = (j1 - j0)*(i - i0) / (i1 - i0) + j0;
		drawPixel(i, j, red, green, blue);
	}
}

void drawOnPixelBuffer()
{
	//std::memset(pixels, 1.0f, sizeof(float)*width*height * 3); // doesn't work
	fill_n(pixels, width*height * 3, 1.0f);	// white background

	//Question 3 Part
	vector<GeometricObjectInterface*> obj_list;
	obj_list.push_back(new GeometricObject<Circle>);
	obj_list.push_back(new GeometricObject<Box>);
	for (auto itr : obj_list)
	{
		/*for (int i = START_COORDINATES; i < START_COORDINATES+(12*ONE_OBJ); i += ONE_OBJ)
		{
			itr->setElements(i,i,40,5);*/
			itr->draw();
		//}
	}
}

//w is the width of the circle'outer shell
void drawCircle(const int x, const int y, const int r, const int w, const float red, const float green, const float blue)
{
	for (int a = 0; a < width; a++)
	{
		for (int b = 0; b < height; b++)
		{

			if (sqrt((x - a)*(x - a) + (y - b)*(y - b)) <= r)
			{
				if (sqrt((x - a)*(x - a) + (y - b)*(y - b)) >= r - w)
					drawPixel(a, b, red, green, blue);
			}
		}
	}
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkHierarchicalDataInformation.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkHierarchicalDataInformation.h"

#include "vtkHierarchicalDataInformation.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"

vtkCxxRevisionMacro(vtkHierarchicalDataInformation, "1.1");
vtkStandardNewMacro(vtkHierarchicalDataInformation);

#include <vtkstd/vector>

struct vtkHierarchicalDataInformationInternal
{
  typedef vtkstd::vector<vtkSmartPointer<vtkInformation> > LevelInformationType;
  typedef vtkstd::vector<LevelInformationType> DataInformationType;

  DataInformationType DataInformation;
};

//----------------------------------------------------------------------------
vtkHierarchicalDataInformation::vtkHierarchicalDataInformation()
{
  this->Internal = new vtkHierarchicalDataInformationInternal;
}

//----------------------------------------------------------------------------
vtkHierarchicalDataInformation::~vtkHierarchicalDataInformation()
{
  delete this->Internal;
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::Clear()
{
  this->Internal->DataInformation.clear();
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::DeepCopy(
  vtkHierarchicalDataInformation* from)
{
  unsigned int numLevels = from->GetNumberOfLevels();
  this->SetNumberOfLevels(numLevels);
  for (unsigned int i=0; i<numLevels; i++)
    {
    unsigned int numDataSets = from->GetNumberOfDataSets(i);
    this->SetNumberOfDataSets(i, numDataSets);
    for (unsigned int j=0; j<numDataSets; j++)
      {
      vtkInformation* toInf   = this->GetInformation(i, j);
      vtkInformation* fromInf = from->GetInformation(i, j);
      toInf->Copy(fromInf);
      }
    }
}

//----------------------------------------------------------------------------
unsigned int vtkHierarchicalDataInformation::GetNumberOfLevels()
{
  return this->Internal->DataInformation.size();
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::SetNumberOfLevels(unsigned int numLevels)
{
  if (numLevels == this->GetNumberOfLevels())
    {
    return;
    }
  this->Internal->DataInformation.resize(numLevels);

  this->Modified();
}

//----------------------------------------------------------------------------
unsigned int vtkHierarchicalDataInformation::GetNumberOfDataSets(
  unsigned int level)
{
  if (this->Internal->DataInformation.size() <= level)
    {
    return 0;
    }

  vtkHierarchicalDataInformationInternal::LevelInformationType& linf =
    this->Internal->DataInformation[level];

  return linf.size();
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::SetNumberOfDataSets(
  unsigned int level, unsigned int numDataSets)
{
  if (numDataSets == this->GetNumberOfDataSets(level))
    {
    return;
    }
  // Make sure that there is a vector allocated for this level
  if (this->Internal->DataInformation.size() <= level)
    {
    this->SetNumberOfLevels(level+1);
    }

  vtkHierarchicalDataInformationInternal::LevelInformationType& linf =
    this->Internal->DataInformation[level];
  linf.resize(numDataSets);

  this->Modified();
}

//----------------------------------------------------------------------------
vtkInformation* vtkHierarchicalDataInformation::GetInformation(
  unsigned int level, unsigned int id)
{
  if (this->Internal->DataInformation.size() <= level)
    {
    return 0;
    }

  vtkHierarchicalDataInformationInternal::LevelInformationType& linf =
    this->Internal->DataInformation[level];
  if (linf.size() <= id)
    {
    return 0;
    }

  vtkInformation* inf = linf[id].GetPointer();
  if (!inf)
    {
    inf = vtkInformation::New();
    linf[id] = inf;
    inf->Delete();
    }

  return inf;
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

<commit_msg>BUG: Do not resize the information to shrink<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkHierarchicalDataInformation.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkHierarchicalDataInformation.h"

#include "vtkHierarchicalDataInformation.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"

vtkCxxRevisionMacro(vtkHierarchicalDataInformation, "1.2");
vtkStandardNewMacro(vtkHierarchicalDataInformation);

#include <vtkstd/vector>

struct vtkHierarchicalDataInformationInternal
{
  typedef vtkstd::vector<vtkSmartPointer<vtkInformation> > LevelInformationType;
  typedef vtkstd::vector<LevelInformationType> DataInformationType;

  DataInformationType DataInformation;
};

//----------------------------------------------------------------------------
vtkHierarchicalDataInformation::vtkHierarchicalDataInformation()
{
  this->Internal = new vtkHierarchicalDataInformationInternal;
}

//----------------------------------------------------------------------------
vtkHierarchicalDataInformation::~vtkHierarchicalDataInformation()
{
  delete this->Internal;
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::Clear()
{
  this->Internal->DataInformation.clear();
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::DeepCopy(
  vtkHierarchicalDataInformation* from)
{
  unsigned int numLevels = from->GetNumberOfLevels();
  this->SetNumberOfLevels(numLevels);
  for (unsigned int i=0; i<numLevels; i++)
    {
    unsigned int numDataSets = from->GetNumberOfDataSets(i);
    this->SetNumberOfDataSets(i, numDataSets);
    for (unsigned int j=0; j<numDataSets; j++)
      {
      vtkInformation* toInf   = this->GetInformation(i, j);
      vtkInformation* fromInf = from->GetInformation(i, j);
      toInf->Copy(fromInf);
      }
    }
}

//----------------------------------------------------------------------------
unsigned int vtkHierarchicalDataInformation::GetNumberOfLevels()
{
  return this->Internal->DataInformation.size();
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::SetNumberOfLevels(unsigned int numLevels)
{
  if (numLevels <= this->GetNumberOfLevels())
    {
    return;
    }
  this->Internal->DataInformation.resize(numLevels);

  this->Modified();
}

//----------------------------------------------------------------------------
unsigned int vtkHierarchicalDataInformation::GetNumberOfDataSets(
  unsigned int level)
{
  if (this->Internal->DataInformation.size() <= level)
    {
    return 0;
    }

  vtkHierarchicalDataInformationInternal::LevelInformationType& linf =
    this->Internal->DataInformation[level];

  return linf.size();
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::SetNumberOfDataSets(
  unsigned int level, unsigned int numDataSets)
{
  if (numDataSets <= this->GetNumberOfDataSets(level))
    {
    return;
    }
  // Make sure that there is a vector allocated for this level
  if (this->Internal->DataInformation.size() <= level)
    {
    this->SetNumberOfLevels(level+1);
    }

  vtkHierarchicalDataInformationInternal::LevelInformationType& linf =
    this->Internal->DataInformation[level];
  linf.resize(numDataSets);

  this->Modified();
}

//----------------------------------------------------------------------------
vtkInformation* vtkHierarchicalDataInformation::GetInformation(
  unsigned int level, unsigned int id)
{
  if (this->Internal->DataInformation.size() <= level)
    {
    return 0;
    }

  vtkHierarchicalDataInformationInternal::LevelInformationType& linf =
    this->Internal->DataInformation[level];
  if (linf.size() <= id)
    {
    return 0;
    }

  vtkInformation* inf = linf[id].GetPointer();
  if (!inf)
    {
    inf = vtkInformation::New();
    linf[id] = inf;
    inf->Delete();
    }

  return inf;
}

//----------------------------------------------------------------------------
void vtkHierarchicalDataInformation::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

<|endoftext|>


<commit_before>#include "vtkIncrementalForceLayout.h"

#include "vtkCommand.h"
#include "vtkFloatArray.h"
#include "vtkGraph.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkSmartPointer.h"
#include "vtkVariant.h"
#include "vtkVector.h"

#include <utility>
#include <vector>

class Quad
{
public:
  Quad();
  Quad(float *points, int n, float x1, float y1, float x2, float y2);
  ~Quad();

  void Insert(vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2);
  void InsertChild(vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2);
  void ForceAccumulate(float alpha, float charge);
  void Repulse(vtkVector2f &force, vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2, float theta);

  bool Leaf;
  bool ValidPoint;
  vtkVector2f Point;
  vtkIdType Vertex;
  float PointCharge;
  vtkVector2f Center;
  float Charge;
  Quad *Nodes[4];
};

Quad::Quad()
{
  this->Leaf = true;
  this->ValidPoint = false;
  this->Point = vtkVector2f(0.0f, 0.0f);
  this->Vertex = 0;
  this->Charge = 0.0f;
  this->Nodes[0] = this->Nodes[1] = this->Nodes[2] = this->Nodes[3] = 0;
}

Quad::Quad(float *points, int n, float x1, float y1, float x2, float y2)
{
  this->Leaf = true;
  this->ValidPoint = false;
  this->Point = vtkVector2f(0.0f, 0.0f);
  this->Vertex = 0;
  this->Nodes[0] = this->Nodes[1] = this->Nodes[2] = this->Nodes[3] = 0;

  // Insert points
  for (int i = 0; i < n; ++i)
    {
    vtkVector2f p = *reinterpret_cast<vtkVector2f*>(points + 3*i);
    this->Insert(p, i, x1, y1, x2, y2);
    }
}

Quad::~Quad()
{
  for (int i = 0; i < 4; ++i)
    {
    if (this->Nodes[i])
      {
      delete this->Nodes[i];
      this->Nodes[i] = 0;
      }
    }
}

void Quad::Insert(vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2) {
  if (this->Leaf)
    {
    if (this->ValidPoint) {
      vtkVector2f v = this->Point;
      // If the point at this leaf node is at the same position as the new
      // point we are adding, we leave the point associated with the
      // internal node while adding the new point to a child node. This
      // avoids infinite recursion.
      if ((fabs(v.GetX() - p.GetX()) + fabs(v.GetY() - p.GetY())) < .01) {
        this->InsertChild(p, vert, x1, y1, x2, y2);
      } else {
        this->ValidPoint = false;
        this->InsertChild(v, this->Vertex, x1, y1, x2, y2);
        this->InsertChild(p, vert, x1, y1, x2, y2);
      }
    } else {
      this->Point = p;
      this->ValidPoint = true;
      this->Vertex = vert;
    }
  } else {
    this->InsertChild(p, vert, x1, y1, x2, y2);
  }
}

// Recursively inserts the specified point p into a descendant of node n. The
// bounds are defined by [x1, x2] and [y1, y2].
void Quad::InsertChild(vtkVector2f& p, vtkIdType vert, float x1, float y1, float x2, float y2)
{
  // Compute the split point, and the quadrant in which to insert p.
  float sx = (x1 + x2) * .5f;
  float sy = (y1 + y2) * .5f;
  bool right = p.GetX() >= sx;
  bool bottom = p.GetY() >= sy;
  int i = (bottom << 1) + right;

  // Recursively insert into the child node.
  this->Leaf = false;
  if (!this->Nodes[i])
    {
    this->Nodes[i] = new Quad();
    }
  Quad *n = this->Nodes[i];

  // Update the bounds as we recurse.
  if (right) x1 = sx; else x2 = sx;
  if (bottom) y1 = sy; else y2 = sy;
  n->Insert(p, vert, x1, y1, x2, y2);
}

void Quad::ForceAccumulate(float alpha, float charge)
{
  float cx = 0.0f;
  float cy = 0.0f;
  this->Charge = 0.0f;
  if (!this->Leaf)
    {
    for (int i = 0; i < 4; ++i)
      {
      Quad *c = this->Nodes[i];
      if (!c)
        {
        continue;
        }
      c->ForceAccumulate(alpha, charge);
      this->Charge += c->Charge;
      cx += c->Charge * c->Center.GetX();
      cy += c->Charge * c->Center.GetY();
      }
    }
  if (this->ValidPoint)
    {
    // Jitter internal nodes that are coincident
    if (!this->Leaf)
      {
      this->Point.SetX(this->Point.GetX() + static_cast<float>(vtkMath::Random()) - 0.5f);
      this->Point.SetY(this->Point.GetY() + static_cast<float>(vtkMath::Random()) - 0.5f);
      }
    float k = alpha * charge;
    this->PointCharge = k;
    this->Charge += this->PointCharge;
    cx += k * this->Point.GetX();
    cy += k * this->Point.GetY();
    }
  this->Center = vtkVector2f(cx / this->Charge, cy / this->Charge);
}

void Quad::Repulse(vtkVector2f &force, vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2, float theta)
{
  if (this->Vertex != vert)
    {
    float dx = this->Center.GetX() - p.GetX();
    float dy = this->Center.GetY() - p.GetY();
    float dn = 1.0f / sqrt(dx * dx + dy * dy);

    // Barnes-Hut criterion.
    if ((x2 - x1) * dn < theta)
      {
      float k = this->Charge * dn * dn;
      force.SetX(force.GetX() - dx * k);
      force.SetY(force.GetY() - dy * k);
      return;
      }
    else if (this->ValidPoint && !vtkMath::IsNan(dn) && !vtkMath::IsInf(dn))
      {
      float k = this->PointCharge * dn * dn;
      force.SetX(force.GetX() - dx * k);
      force.SetY(force.GetY() - dy * k);
      }
    }
  if (this->Charge)
    {
    float sx = (x1 + x2) * .5;
    float sy = (y1 + y2) * .5;
    if (this->Nodes[0]) this->Nodes[0]->Repulse(force, p, vert, x1, y1, sx, sy, theta);
    if (this->Nodes[1]) this->Nodes[1]->Repulse(force, p, vert, sx, y1, x2, sy, theta);
    if (this->Nodes[2]) this->Nodes[2]->Repulse(force, p, vert, x1, sy, sx, y2, theta);
    if (this->Nodes[3]) this->Nodes[3]->Repulse(force, p, vert, sx, sy, x2, y2, theta);
    }
}

class vtkIncrementalForceLayout::Implementation
{
public:
  Implementation()
    {
    }

  vtkVector2f& GetPosition(vtkIdType i)
    {
    return *(reinterpret_cast<vtkVector2f*>(this->Position + 3*i));
    }

  float *Position;
  std::vector<vtkVector2f> LastPosition;
};

vtkStandardNewMacro(vtkIncrementalForceLayout);
vtkCxxSetObjectMacro(vtkIncrementalForceLayout, Graph, vtkGraph);

vtkIncrementalForceLayout::vtkIncrementalForceLayout()
{
  this->Impl = new Implementation();
  this->Graph = 0;
  this->Fixed = -1;
  this->GravityPoint = vtkVector2f(200.0f, 200.0f);
  this->Alpha = 0.1f;
  this->Theta = 0.8f;
  this->Charge = -50.0f;
  this->Strength = 2.0f;
  this->Distance = 20.0f;
  this->Gravity = 0.05f;
  this->Friction = 1.0f;
}

vtkIncrementalForceLayout::~vtkIncrementalForceLayout()
{
  delete this->Impl;
  this->SetGraph(0);
}

void vtkIncrementalForceLayout::UpdatePositions()
{
  if (!this->Graph)
    {
    return;
    }

  vtkIdType numVerts = this->Graph->GetNumberOfVertices();
  vtkIdType numEdges = this->Graph->GetNumberOfEdges();
  this->Impl->Position = vtkFloatArray::SafeDownCast(this->Graph->GetPoints()->GetData())->GetPointer(0);
  while (numVerts >= static_cast<vtkIdType>(this->Impl->LastPosition.size()))
    {
    this->Impl->LastPosition.push_back(vtkVector2f(0.0f, 0.0f));
    }

  // Gauss-Seidel relaxation for links
  for (vtkIdType e = 0; e < numEdges; ++e)
    {
    vtkIdType s = this->Graph->GetSourceVertex(e);
    vtkIdType t = this->Graph->GetTargetVertex(e);
    vtkVector2f& sPos = this->Impl->GetPosition(s);
    vtkVector2f& tPos = this->Impl->GetPosition(t);
    float x = tPos.GetX() - sPos.GetX();
    float y = tPos.GetY() - sPos.GetY();
    if (float l = (x * x + y * y))
      {
      float sqrtl = sqrt(l);
      l = this->Alpha * this->Strength * (sqrtl - this->Distance) / sqrtl;
      x *= l;
      y *= l;
      float sWeight = 1.0f;
      float tWeight = 1.0f;
      float k = sWeight / (tWeight + sWeight);
      if (t != this->Fixed)
        {
        tPos.SetX(tPos.GetX() - x * k);
        tPos.SetY(tPos.GetY() - y * k);
        }
      k = 1 - k;
      if (s != this->Fixed)
        {
        sPos.SetX(sPos.GetX() + x * k);
        sPos.SetY(sPos.GetY() + y * k);
        }
      }
    }

  // Gravity forces
  float k = this->Alpha * this->Gravity;
  if (k)
    {
    float x = this->GravityPoint.GetX();
    float y = this->GravityPoint.GetY();
    for (vtkIdType v = 0; v < numVerts; ++v)
      {
      vtkVector2f& vPos = this->Impl->GetPosition(v);
      if (v != this->Fixed)
        {
        vPos.SetX(vPos.GetX() + (x - vPos.GetX()) * k);
        vPos.SetY(vPos.GetY() + (y - vPos.GetY()) * k);
        }
      }
    }

  // Bounds
  float x1 = VTK_FLOAT_MAX;
  float x2 = VTK_FLOAT_MIN;
  float y1 = VTK_FLOAT_MAX;
  float y2 = VTK_FLOAT_MIN;
  for (vtkIdType i = 0; i < numVerts; ++i)
    {
    vtkVector2f p = this->Impl->GetPosition(i);
    x1 = std::min(x1, p.GetX());
    x2 = std::max(x2, p.GetX());
    y1 = std::min(y1, p.GetY());
    y2 = std::max(y2, p.GetY());
    }

  // Squarify the bounds.
  float dx = x2 - x1;
  float dy = y2 - y1;
  if (dx > dy)
    {
    y2 = y1 + dx;
    }
  else
    {
    x2 = x1 + dy;
    }

  // Charge force
  Quad *tree = new Quad(this->Impl->Position, numVerts, x1, y1, x2, y2);
  tree->ForceAccumulate(this->Alpha, this->Charge);
  for (vtkIdType v = 0; v < numVerts; ++v)
    {
    if (v != this->Fixed)
      {
      tree->Repulse(this->Impl->LastPosition[v], this->Impl->GetPosition(v), v, x1, y1, x2, y2, this->Theta);
      }
    }
  delete tree;

  // Position Verlet integration
  for (vtkIdType v = 0; v < numVerts; ++v)
    {
    vtkVector2f& vPos = this->Impl->GetPosition(v);
    vtkVector2f& vLastPos = this->Impl->LastPosition[v];
    if (v != this->Fixed)
      {
      vPos.SetX(vPos.GetX() - (vLastPos.GetX() - vPos.GetX()) * this->Friction);
      vPos.SetY(vPos.GetY() - (vLastPos.GetY() - vPos.GetY()) * this->Friction);
      vLastPos = vPos;
      }
    }
}

void vtkIncrementalForceLayout::SetFixed(vtkIdType v)
{
  if (this->Fixed >= 0)
    {
    this->Impl->LastPosition[this->Fixed] = this->Impl->GetPosition(this->Fixed);
    }
  this->Fixed = v;
}

void vtkIncrementalForceLayout::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<commit_msg>Remove layout jitter by weighting vertices by degree<commit_after>#include "vtkIncrementalForceLayout.h"

#include "vtkCommand.h"
#include "vtkDirectedGraph.h"
#include "vtkFloatArray.h"
#include "vtkGraph.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkSmartPointer.h"
#include "vtkVariant.h"
#include "vtkVector.h"

#include <utility>
#include <vector>

class Quad
{
public:
  Quad();
  Quad(float *points, int n, float x1, float y1, float x2, float y2);
  ~Quad();

  void Insert(vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2);
  void InsertChild(vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2);
  void ForceAccumulate(float alpha, float charge);
  bool Repulse(vtkVector2f &prev, vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2, float theta);
  void Visit(vtkVector2f &prev, vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2, float theta);

  bool Leaf;
  bool ValidPoint;
  vtkVector2f Point;
  vtkIdType Vertex;
  float PointCharge;
  vtkVector2f Center;
  float Charge;
  Quad *Nodes[4];
};

Quad::Quad()
{
  this->Leaf = true;
  this->ValidPoint = false;
  this->Point = vtkVector2f(0.0f, 0.0f);
  this->Vertex = 0;
  this->Charge = 0.0f;
  this->Nodes[0] = this->Nodes[1] = this->Nodes[2] = this->Nodes[3] = 0;
}

Quad::Quad(float *points, int n, float x1, float y1, float x2, float y2)
{
  this->Leaf = true;
  this->ValidPoint = false;
  this->Point = vtkVector2f(0.0f, 0.0f);
  this->Vertex = 0;
  this->Nodes[0] = this->Nodes[1] = this->Nodes[2] = this->Nodes[3] = 0;

  // Insert points
  for (int i = 0; i < n; ++i)
    {
    vtkVector2f p = *reinterpret_cast<vtkVector2f*>(points + 3*i);
    this->Insert(p, i, x1, y1, x2, y2);
    }
}

Quad::~Quad()
{
  for (int i = 0; i < 4; ++i)
    {
    if (this->Nodes[i])
      {
      delete this->Nodes[i];
      this->Nodes[i] = 0;
      }
    }
}

void Quad::Insert(vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2) {
  if (vtkMath::IsNan(p.GetX()) || vtkMath::IsNan(p.GetY()))
    {
    return;
    }
  if (this->Leaf)
    {
    if (this->ValidPoint) {
      vtkVector2f v = this->Point;
      // If the point at this leaf node is at the same position as the new
      // point we are adding, we leave the point associated with the
      // internal node while adding the new point to a child node. This
      // avoids infinite recursion.
      if ((fabs(v.GetX() - p.GetX()) + fabs(v.GetY() - p.GetY())) < .01) {
        this->InsertChild(p, vert, x1, y1, x2, y2);
      } else {
        this->ValidPoint = false;
        this->InsertChild(v, this->Vertex, x1, y1, x2, y2);
        this->InsertChild(p, vert, x1, y1, x2, y2);
      }
    } else {
      this->Point = p;
      this->ValidPoint = true;
      this->Vertex = vert;
    }
  } else {
    this->InsertChild(p, vert, x1, y1, x2, y2);
  }
}

// Recursively inserts the specified point p into a descendant of node n. The
// bounds are defined by [x1, x2] and [y1, y2].
void Quad::InsertChild(vtkVector2f& p, vtkIdType vert, float x1, float y1, float x2, float y2)
{
  // Compute the split point, and the quadrant in which to insert p.
  float sx = (x1 + x2) * .5f;
  float sy = (y1 + y2) * .5f;
  bool right = p.GetX() >= sx;
  bool bottom = p.GetY() >= sy;
  int i = (bottom << 1) + right;

  // Recursively insert into the child node.
  this->Leaf = false;
  if (!this->Nodes[i])
    {
    this->Nodes[i] = new Quad();
    }
  Quad *n = this->Nodes[i];

  // Update the bounds as we recurse.
  if (right) x1 = sx; else x2 = sx;
  if (bottom) y1 = sy; else y2 = sy;
  n->Insert(p, vert, x1, y1, x2, y2);
}

void Quad::ForceAccumulate(float alpha, float charge)
{
  float cx = 0.0f;
  float cy = 0.0f;
  this->Charge = 0.0f;
  if (!this->Leaf)
    {
    for (int i = 0; i < 4; ++i)
      {
      Quad *c = this->Nodes[i];
      if (!c)
        {
        continue;
        }
      c->ForceAccumulate(alpha, charge);
      this->Charge += c->Charge;
      cx += c->Charge * c->Center.GetX();
      cy += c->Charge * c->Center.GetY();
      }
    }
  if (this->ValidPoint)
    {
    // Jitter internal nodes that are coincident
    if (!this->Leaf)
      {
      this->Point.SetX(this->Point.GetX() + static_cast<float>(vtkMath::Random()) - 0.5f);
      this->Point.SetY(this->Point.GetY() + static_cast<float>(vtkMath::Random()) - 0.5f);
      }
    float k = alpha * charge;
    this->PointCharge = k;
    this->Charge += this->PointCharge;
    cx += k * this->Point.GetX();
    cy += k * this->Point.GetY();
    }
  this->Center = vtkVector2f(cx / this->Charge, cy / this->Charge);
}

bool Quad::Repulse(vtkVector2f &prev, vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2, float theta)
{
  if (this->Vertex != vert)
    {
    float dx = this->Center.GetX() - p.GetX();
    float dy = this->Center.GetY() - p.GetY();
    float dn = 1.0f / sqrt(dx * dx + dy * dy);

    // Barnes-Hut criterion.
    if ((x2 - x1) * dn < theta)
      {
      float k = this->Charge * dn * dn;
      prev.SetX(prev.GetX() - dx * k);
      prev.SetY(prev.GetY() - dy * k);
      return true;
      }
    else if (this->ValidPoint && !vtkMath::IsNan(dn) && !vtkMath::IsInf(dn))
      {
      float k = this->PointCharge * dn * dn;
      prev.SetX(prev.GetX() - dx * k);
      prev.SetY(prev.GetY() - dy * k);
      }
    }
  return !this->Charge;
}

void Quad::Visit(vtkVector2f &prev, vtkVector2f &p, vtkIdType vert, float x1, float y1, float x2, float y2, float theta)
{
  if (!this->Repulse(prev, p, vert, x1, y1, x2, y2, theta))
    {
    float sx = (x1 + x2) * .5;
    float sy = (y1 + y2) * .5;
    if (this->Nodes[0]) this->Nodes[0]->Visit(prev, p, vert, x1, y1, sx, sy, theta);
    if (this->Nodes[1]) this->Nodes[1]->Visit(prev, p, vert, sx, y1, x2, sy, theta);
    if (this->Nodes[2]) this->Nodes[2]->Visit(prev, p, vert, x1, sy, sx, y2, theta);
    if (this->Nodes[3]) this->Nodes[3]->Visit(prev, p, vert, sx, sy, x2, y2, theta);
    }
}

class vtkIncrementalForceLayout::Implementation
{
public:
  Implementation()
    {
    }

  vtkVector2f& GetPosition(vtkIdType i)
    {
    return *(reinterpret_cast<vtkVector2f*>(this->Position + 3*i));
    }

  float *Position;
  std::vector<vtkVector2f> LastPosition;
};

vtkStandardNewMacro(vtkIncrementalForceLayout);
vtkCxxSetObjectMacro(vtkIncrementalForceLayout, Graph, vtkGraph);

vtkIncrementalForceLayout::vtkIncrementalForceLayout()
{
  this->Impl = new Implementation();
  this->Graph = 0;
  this->Fixed = -1;
  this->GravityPoint = vtkVector2f(200.0f, 200.0f);
  this->Alpha = 0.1f;
  this->Theta = 0.8f;
  this->Charge = -50.0f;
  this->Strength = 1.0f;
  this->Distance = 20.0f;
  this->Gravity = 0.1f;
  this->Friction = 0.9f;
}

vtkIncrementalForceLayout::~vtkIncrementalForceLayout()
{
  delete this->Impl;
  this->SetGraph(0);
}

void vtkIncrementalForceLayout::UpdatePositions()
{
  if (!this->Graph)
    {
    return;
    }

  vtkIdType numVerts = this->Graph->GetNumberOfVertices();
  vtkIdType numEdges = this->Graph->GetNumberOfEdges();
  this->Impl->Position = vtkFloatArray::SafeDownCast(this->Graph->GetPoints()->GetData())->GetPointer(0);
  while (numVerts >= static_cast<vtkIdType>(this->Impl->LastPosition.size()))
    {
    this->Impl->LastPosition.push_back(vtkVector2f(0.0f, 0.0f));
    }

  // Swap pos and lastpos for fixed node
  if (this->Fixed >= 0 && this->Fixed < numVerts)
    {
    vtkVector2f &pos = this->Impl->GetPosition(this->Fixed);
    vtkVector2f temp = pos;
    pos = this->Impl->LastPosition[this->Fixed];
    this->Impl->LastPosition[this->Fixed] = temp;
    }

  // Gauss-Seidel relaxation for links
  bool directed = vtkDirectedGraph::SafeDownCast(this->Graph);
  for (vtkIdType e = 0; e < numEdges; ++e)
    {
    vtkIdType s = this->Graph->GetSourceVertex(e);
    vtkIdType t = this->Graph->GetTargetVertex(e);
    vtkVector2f& sPos = this->Impl->GetPosition(s);
    vtkVector2f& tPos = this->Impl->GetPosition(t);
    float x = tPos.GetX() - sPos.GetX();
    float y = tPos.GetY() - sPos.GetY();
    vtkIdType degreeS;
    vtkIdType degreeT;
    if (directed)
      {
      degreeS = this->Graph->GetOutDegree(s) + this->Graph->GetInDegree(s);
      degreeT = this->Graph->GetOutDegree(t) + this->Graph->GetInDegree(t);
      }
    else
      {
      degreeS = this->Graph->GetOutDegree(s);
      degreeT = this->Graph->GetOutDegree(t);
      }
    if (float l = (x * x + y * y))
      {
      float sqrtl = sqrt(l);
      l = this->Alpha * this->Strength * (sqrtl - this->Distance) / sqrtl;
      x *= l;
      y *= l;
      float sWeight = degreeS;
      float tWeight = degreeT;
      float k = sWeight / (tWeight + sWeight);
      if (t != this->Fixed)
        {
        tPos.SetX(tPos.GetX() - x * k);
        tPos.SetY(tPos.GetY() - y * k);
        }
      k = 1 - k;
      if (s != this->Fixed)
        {
        sPos.SetX(sPos.GetX() + x * k);
        sPos.SetY(sPos.GetY() + y * k);
        }
      }
    }

  // Gravity forces
  float k = this->Alpha * this->Gravity;
  if (k)
    {
    float x = this->GravityPoint.GetX();
    float y = this->GravityPoint.GetY();
    for (vtkIdType v = 0; v < numVerts; ++v)
      {
      vtkVector2f& vPos = this->Impl->GetPosition(v);
      if (v != this->Fixed)
        {
        vPos.SetX(vPos.GetX() + (x - vPos.GetX()) * k);
        vPos.SetY(vPos.GetY() + (y - vPos.GetY()) * k);
        }
      }
    }

  // Bounds
  float x1 = VTK_FLOAT_MAX;
  float x2 = VTK_FLOAT_MIN;
  float y1 = VTK_FLOAT_MAX;
  float y2 = VTK_FLOAT_MIN;
  for (vtkIdType i = 0; i < numVerts; ++i)
    {
    vtkVector2f p = this->Impl->GetPosition(i);
    x1 = std::min(x1, p.GetX());
    x2 = std::max(x2, p.GetX());
    y1 = std::min(y1, p.GetY());
    y2 = std::max(y2, p.GetY());
    }

  // Squarify the bounds.
  float dx = x2 - x1;
  float dy = y2 - y1;
  if (dx > dy)
    {
    y2 = y1 + dx;
    }
  else
    {
    x2 = x1 + dy;
    }

  // Charge force
  Quad *tree = new Quad(this->Impl->Position, numVerts, x1, y1, x2, y2);
  tree->ForceAccumulate(this->Alpha, this->Charge);
  for (vtkIdType v = 0; v < numVerts; ++v)
    {
    if (v != this->Fixed)
      {
      tree->Visit(this->Impl->LastPosition[v], this->Impl->GetPosition(v), v, x1, y1, x2, y2, this->Theta);
      }
    }
  delete tree;

  // Position Verlet integration
  for (vtkIdType v = 0; v < numVerts; ++v)
    {
    vtkVector2f& vPos = this->Impl->GetPosition(v);
    vtkVector2f& vLastPos = this->Impl->LastPosition[v];
    if (v != this->Fixed)
      {
      vPos.SetX(vPos.GetX() - (vLastPos.GetX() - vPos.GetX()) * this->Friction);
      vPos.SetY(vPos.GetY() - (vLastPos.GetY() - vPos.GetY()) * this->Friction);
      vLastPos = vPos;
      }
    else
      {
      vPos = vLastPos;
      }
    }
}

void vtkIncrementalForceLayout::SetFixed(vtkIdType v)
{
  if (this->Fixed >= 0)
    {
    this->Impl->LastPosition[this->Fixed] = this->Impl->GetPosition(this->Fixed);
    }
  this->Fixed = v;
}

void vtkIncrementalForceLayout::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<|endoftext|>


<commit_before><commit_msg>Remove flaky label from ParseFeed tests.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"

static void DispatchOnConnect(int source_port_id, const std::string& name,
                              const std::string& tab_json) {
  ListValue args;
  args.Set(0, Value::CreateIntegerValue(source_port_id));
  args.Set(1, Value::CreateStringValue(name));
  args.Set(2, Value::CreateStringValue(tab_json));
  args.Set(3, Value::CreateStringValue(""));  // extension ID is empty for tests
  args.Set(4, Value::CreateStringValue(""));  // extension ID is empty for tests
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL());
}

static void DispatchOnDisconnect(int source_port_id) {
  ListValue args;
  args.Set(0, Value::CreateIntegerValue(source_port_id));
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false,
      GURL());
}

static void DispatchOnMessage(const std::string& message, int source_port_id) {
  ListValue args;
  args.Set(0, Value::CreateStringValue(message));
  args.Set(1, Value::CreateIntegerValue(source_port_id));
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL());
}

// Tests that the bindings for opening a channel to an extension and sending
// and receiving messages through that channel all works.
TEST_F(RenderViewTest, ExtensionMessagesOpenChannel) {
  render_thread_.sink().ClearMessages();
  LoadHTML("");
  ExecuteJavaScript(
    "var port = chrome.extension.connect({name:'testName'});"
    "port.onMessage.addListener(doOnMessage);"
    "port.postMessage({message: 'content ready'});"
    "function doOnMessage(msg, port) {"
    "  alert('content got: ' + msg.val);"
    "}");

  // Verify that we opened a channel and sent a message through it.
  const IPC::Message* open_channel_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_OpenChannelToExtension::ID);
  ASSERT_TRUE(open_channel_msg);
  void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg);
  ViewHostMsg_OpenChannelToExtension::SendParam open_params;
  ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params));
  EXPECT_EQ("testName", open_params.d);

  const IPC::Message* post_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_ExtensionPostMessage::ID);
  ASSERT_TRUE(post_msg);
  ViewHostMsg_ExtensionPostMessage::Param post_params;
  ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
  EXPECT_EQ("{\"message\":\"content ready\"}", post_params.b);

  // Now simulate getting a message back from the other side.
  render_thread_.sink().ClearMessages();
  const int kPortId = 0;
  DispatchOnMessage("{\"val\": 42}", kPortId);

  // Verify that we got it.
  const IPC::Message* alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"content got: 42", alert_param.a);
}

// Tests that the bindings for handling a new channel connection and channel
// closing all works.
TEST_F(RenderViewTest, ExtensionMessagesOnConnect) {
  LoadHTML("");
  ExecuteJavaScript(
    "chrome.extension.onConnect.addListener(function (port) {"
    "  port.test = 24;"
    "  port.onMessage.addListener(doOnMessage);"
    "  port.onDisconnect.addListener(doOnDisconnect);"
    "  port.postMessage({message: 'onconnect from ' + port.tab.url + "
    "                   ' name ' + port.name});"
    "});"
    "function doOnMessage(msg, port) {"
    "  alert('got: ' + msg.val);"
    "}"
    "function doOnDisconnect(port) {"
    "  alert('disconnected: ' + port.test);"
    "}");

  render_thread_.sink().ClearMessages();

  // Simulate a new connection being opened.
  const int kPortId = 0;
  const std::string kPortName = "testName";
  DispatchOnConnect(kPortId, kPortName, "{\"url\":\"foo://bar\"}");

  // Verify that we handled the new connection by posting a message.
  const IPC::Message* post_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_ExtensionPostMessage::ID);
  ASSERT_TRUE(post_msg);
  ViewHostMsg_ExtensionPostMessage::Param post_params;
  ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
  std::string expected_msg =
      "{\"message\":\"onconnect from foo://bar name " + kPortName + "\"}";
  EXPECT_EQ(expected_msg, post_params.b);

  // Now simulate getting a message back from the channel opener.
  render_thread_.sink().ClearMessages();
  DispatchOnMessage("{\"val\": 42}", kPortId);

  // Verify that we got it.
  const IPC::Message* alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  void* iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"got: 42", alert_param.a);

  // Now simulate the channel closing.
  render_thread_.sink().ClearMessages();
  DispatchOnDisconnect(kPortId);

  // Verify that we got it.
  alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"disconnected: 24", alert_param.a);
}
<commit_msg>Disable RenderViewTest.ExtensionMessages* since they consistently crash localy and on the bots.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"

static void DispatchOnConnect(int source_port_id, const std::string& name,
                              const std::string& tab_json) {
  ListValue args;
  args.Set(0, Value::CreateIntegerValue(source_port_id));
  args.Set(1, Value::CreateStringValue(name));
  args.Set(2, Value::CreateStringValue(tab_json));
  args.Set(3, Value::CreateStringValue(""));  // extension ID is empty for tests
  args.Set(4, Value::CreateStringValue(""));  // extension ID is empty for tests
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL());
}

static void DispatchOnDisconnect(int source_port_id) {
  ListValue args;
  args.Set(0, Value::CreateIntegerValue(source_port_id));
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false,
      GURL());
}

static void DispatchOnMessage(const std::string& message, int source_port_id) {
  ListValue args;
  args.Set(0, Value::CreateStringValue(message));
  args.Set(1, Value::CreateIntegerValue(source_port_id));
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL());
}

// Tests that the bindings for opening a channel to an extension and sending
// and receiving messages through that channel all works.
TEST_F(RenderViewTest, DISABLED_ExtensionMessagesOpenChannel) {
  render_thread_.sink().ClearMessages();
  LoadHTML("");
  ExecuteJavaScript(
    "var port = chrome.extension.connect({name:'testName'});"
    "port.onMessage.addListener(doOnMessage);"
    "port.postMessage({message: 'content ready'});"
    "function doOnMessage(msg, port) {"
    "  alert('content got: ' + msg.val);"
    "}");

  // Verify that we opened a channel and sent a message through it.
  const IPC::Message* open_channel_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_OpenChannelToExtension::ID);
  ASSERT_TRUE(open_channel_msg);
  void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg);
  ViewHostMsg_OpenChannelToExtension::SendParam open_params;
  ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params));
  EXPECT_EQ("testName", open_params.d);

  const IPC::Message* post_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_ExtensionPostMessage::ID);
  ASSERT_TRUE(post_msg);
  ViewHostMsg_ExtensionPostMessage::Param post_params;
  ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
  EXPECT_EQ("{\"message\":\"content ready\"}", post_params.b);

  // Now simulate getting a message back from the other side.
  render_thread_.sink().ClearMessages();
  const int kPortId = 0;
  DispatchOnMessage("{\"val\": 42}", kPortId);

  // Verify that we got it.
  const IPC::Message* alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"content got: 42", alert_param.a);
}

// Tests that the bindings for handling a new channel connection and channel
// closing all works.
TEST_F(RenderViewTest, DISABLED_ExtensionMessagesOnConnect) {
  LoadHTML("");
  ExecuteJavaScript(
    "chrome.extension.onConnect.addListener(function (port) {"
    "  port.test = 24;"
    "  port.onMessage.addListener(doOnMessage);"
    "  port.onDisconnect.addListener(doOnDisconnect);"
    "  port.postMessage({message: 'onconnect from ' + port.tab.url + "
    "                   ' name ' + port.name});"
    "});"
    "function doOnMessage(msg, port) {"
    "  alert('got: ' + msg.val);"
    "}"
    "function doOnDisconnect(port) {"
    "  alert('disconnected: ' + port.test);"
    "}");

  render_thread_.sink().ClearMessages();

  // Simulate a new connection being opened.
  const int kPortId = 0;
  const std::string kPortName = "testName";
  DispatchOnConnect(kPortId, kPortName, "{\"url\":\"foo://bar\"}");

  // Verify that we handled the new connection by posting a message.
  const IPC::Message* post_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_ExtensionPostMessage::ID);
  ASSERT_TRUE(post_msg);
  ViewHostMsg_ExtensionPostMessage::Param post_params;
  ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
  std::string expected_msg =
      "{\"message\":\"onconnect from foo://bar name " + kPortName + "\"}";
  EXPECT_EQ(expected_msg, post_params.b);

  // Now simulate getting a message back from the channel opener.
  render_thread_.sink().ClearMessages();
  DispatchOnMessage("{\"val\": 42}", kPortId);

  // Verify that we got it.
  const IPC::Message* alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  void* iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"got: 42", alert_param.a);

  // Now simulate the channel closing.
  render_thread_.sink().ClearMessages();
  DispatchOnDisconnect(kPortId);

  // Verify that we got it.
  alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"disconnected: 24", alert_param.a);
}
<|endoftext|>