<commit_before>/*
 * Copyright 2015 Nicolas Pope
 */

#include "fdsb/harc.hpp"

#include <thread>
#include <vector>
#include <future>

#include "fdsb/nid.hpp"

using fdsb::Harc;
using fdsb::Nid;

std::unordered_multimap<unsigned long long, Harc*> Harc::s_fabric;

Harc::Harc(const Nid &a, const Nid &b) :
	m_head(null_n),
	m_def(nullptr) {
	m_tail[0] = a;
	m_tail[1] = b;
}

void Harc::add_dependant(Harc &h) {
	m_dependants.push_back(&h);
}

const Nid &Harc::query() {
	while (m_def && m_def->outofdate) {
		// Can we update the definition
		if (!m_def->lock.test_and_set()) {
			m_head = path(m_def->def, this);
			m_def->outofdate = false;
			m_def->lock.clear();
		// Or must we wait on some other thread
		} else {
			// Do something else or yield
			std::this_thread::yield();
		}
	}
	return m_head;
}

void Harc::dirty() {
	if (m_def) m_def->outofdate = true;
	for (auto i : m_dependants) {
		i->dirty();
	}
	m_dependants.clear();
}

void Harc::define(const Nid &n) {
	m_head = n;
	if (m_def) {
		delete m_def;
		m_def = nullptr;
	}
	for (auto i : m_dependants) {
		i->dirty();
	}
	m_dependants.clear();
}

void Harc::define(const std::vector<std::vector<Nid>> &p) {
	if (m_def) delete m_def;
	m_def = new Definition(p);
	dirty();
}

Harc &Harc::operator=(const Nid &n) {
	define(n);
	return *this;
}

bool Harc::operator==(const Nid &n) {
	return query() == n;
}

Harc &Nid::operator[](const Nid &n) {
	return Harc::get(*this, n);
}

Harc &Harc::operator[](const Nid &n) {
	return get(query(), n);
}

Harc &Harc::get(const Nid &a, const Nid &b) {
	Harc *h;
	auto range = s_fabric.equal_range(Nid::dual_hash(a, b));

	for (auto i = range.first; i != range.second; i++) {
		h = i->second;
		if (h->equal_tail(a, b)) {
			return *h;
		}
	}

	h = new Harc(a, b);
	s_fabric.insert({{Nid::dual_hash(a, b), h}});
	return *h;
}

Nid Harc::path_s(const std::vector<Nid> &p, Harc *dep) {
	if (p.size() > 1) {
		Nid temp = p[0];
		for (auto i = ++p.begin(); i != p.end(); ++i) {
			Harc &h = Harc::get(temp, *i);
			if (dep) {
				h.add_dependant(*dep);
			}
			temp = h.query();
		}
		return temp;
	} else if (p.size() == 1) {
		return p[0];
	} else {
		return null_n;
	}
}

std::atomic<int> pool_count(0);

Nid Harc::path(const std::vector<std::vector<Nid>> &p, Harc *dep) {
	int ix = 0;
	std::vector<std::future<Nid>> futures;
	std::vector<Nid> res(p.size());

	// These can all be done in different threads!
	for (auto i : p) {
		if (pool_count < 10) {
			++pool_count;

			futures.push_back(std::async(
				// std::launch::async,
				[](const std::vector<Nid> &p, Nid *res, Harc *dep) -> Nid {
					*res = Harc::path_s(p, dep);
					--pool_count;
					return *res;
				},
				i, &(res.data()[ix++]), dep));
		} else {
			res[ix++] = path_s(i, dep);
		}
	}

	// Final recombination
	for (auto &i : futures) {
		i.get();
	}

	return Harc::path_s(res, dep);
}
<commit_msg>Divide and conquer paths<commit_after>/*
 * Copyright 2015 Nicolas Pope
 */

#include "fdsb/harc.hpp"

#include <thread>
#include <vector>
#include <future>
#include <iostream>

#include "fdsb/nid.hpp"

using fdsb::Harc;
using fdsb::Nid;

std::unordered_multimap<unsigned long long, Harc*> Harc::s_fabric;

Harc::Harc(const Nid &a, const Nid &b) :
	m_head(null_n),
	m_def(nullptr) {
	m_tail[0] = a;
	m_tail[1] = b;
}

void Harc::add_dependant(Harc &h) {
	m_dependants.push_back(&h);
}

const Nid &Harc::query() {
	while (m_def && m_def->outofdate) {
		// Can we update the definition
		if (!m_def->lock.test_and_set()) {
			m_head = path(m_def->def, this);
			m_def->outofdate = false;
			m_def->lock.clear();
		// Or must we wait on some other thread
		} else {
			// Do something else or yield
			std::this_thread::yield();
		}
	}
	return m_head;
}

void Harc::dirty() {
	if (m_def) m_def->outofdate = true;
	for (auto i : m_dependants) {
		i->dirty();
	}
	m_dependants.clear();
}

void Harc::define(const Nid &n) {
	m_head = n;
	if (m_def) {
		delete m_def;
		m_def = nullptr;
	}
	for (auto i : m_dependants) {
		i->dirty();
	}
	m_dependants.clear();
}

void Harc::define(const std::vector<std::vector<Nid>> &p) {
	if (m_def) delete m_def;
	m_def = new Definition(p);
	dirty();
}

Harc &Harc::operator=(const Nid &n) {
	define(n);
	return *this;
}

bool Harc::operator==(const Nid &n) {
	return query() == n;
}

Harc &Nid::operator[](const Nid &n) {
	return Harc::get(*this, n);
}

Harc &Harc::operator[](const Nid &n) {
	return get(query(), n);
}

Harc &Harc::get(const Nid &a, const Nid &b) {
	Harc *h;
	auto range = s_fabric.equal_range(Nid::dual_hash(a, b));

	for (auto i = range.first; i != range.second; i++) {
		h = i->second;
		if (h->equal_tail(a, b)) {
			return *h;
		}
	}

	h = new Harc(a, b);
	s_fabric.insert({{Nid::dual_hash(a, b), h}});
	return *h;
}

Nid Harc::path_s(const std::vector<Nid> &p, Harc *dep) {
	if (p.size() > 1) {
		Nid temp = p[0];
		for (auto i = ++p.begin(); i != p.end(); ++i) {
			Harc &h = Harc::get(temp, *i);
			if (dep) {
				h.add_dependant(*dep);
			}
			temp = h.query();
		}
		return temp;
	} else if (p.size() == 1) {
		return p[0];
	} else {
		return null_n;
	}
}

std::atomic<int> pool_count(4);

Nid Harc::path(const std::vector<std::vector<Nid>> &p, Harc *dep) {
	std::vector<Nid> res(p.size());

	if (p.size() > 1 && pool_count > 0) {
		--pool_count;

		// Divide paths into 2 parts.
		auto middle = p.size() / 2;

		// Asynchronously perform first half
		std::future<bool> fa = std::async(
			std::launch::async,
			[](const std::vector<std::vector<Nid>> &p, Nid *res,
					int s, int e, Harc *dep) {
				for (auto i = s; i < e; ++i) {
					res[i] = Harc::path_s(p[i], dep);
				}
				return true;
			}, p, res.data(), 0, middle, dep);

		for (auto i = middle; i < p.size(); ++i) {
			res[i] = Harc::path_s(p[i], dep);
		}
		fa.get();
		++pool_count;
	} else {
		int ix = 0;

		for (auto i : p) {
			res[ix++] = path_s(i, dep);
		}
	}

	// Final recombination
	return Harc::path_s(res, dep);
}
<|endoftext|>


<commit_before>#include "GRenderContext.h"
#include <fstream>
#include <cmath>
#include "GFrameBufferObject.h"
#include "GLUtil.h"
#include "Util.h"
#include <EGL/egl.h>
#include <vector>

namespace NodeBinding
{

    static std::vector<GRenderContext *> g_RenderContextVC;
    static EGLContext g_eglContext = nullptr;
    static std::vector<GLuint> fboVector;

    GRenderContext::GRenderContext(int width, int height)
        : mWidth(width), mHeight(height), mRatio(2.0),mEglDisplay(EGL_NO_DISPLAY)
    {
        GCanvasConfig config = {true, false};
        this->mCanvas = std::make_shared<gcanvas::GCanvas>("node-gcanvas", config, nullptr);
        mCanvasWidth = width * mRatio;
        mCanvasHeight = height * mRatio;
    }

    GRenderContext::GRenderContext(int width, int height, int ratio)
        : mWidth(width), mHeight(height), mRatio(ratio),mEglDisplay(EGL_NO_DISPLAY)
    {
        GCanvasConfig config = {true, true};
        this->mCanvas = std::make_shared<gcanvas::GCanvas>("node-gcanvas", config, nullptr);
        mCanvasWidth = width * mRatio;
        mCanvasHeight = height * mRatio;
    }

    void GRenderContext::initRenderEnviroment()
    {
#ifdef CONTEXT_ES20
        EGLint ai32ContextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
#endif

        // Step 1 - Get the default display.
        if (!mEglDisplay)
        {
            mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
            // Step 2 - Initialize EGL.
            eglInitialize(mEglDisplay, 0, 0);
        }

#ifdef CONTEXT_ES20
        // Step 3 - Make OpenGL ES the current API.
        eglBindAPI(EGL_OPENGL_ES_API);

        // Step 4 - Specify the required configuration attributes.
        EGLint pi32ConfigAttribs[5];
        pi32ConfigAttribs[0] = EGL_SURFACE_TYPE;
        pi32ConfigAttribs[1] = EGL_WINDOW_BIT;
        pi32ConfigAttribs[2] = EGL_RENDERABLE_TYPE;
        pi32ConfigAttribs[3] = EGL_OPENGL_ES2_BIT;
        pi32ConfigAttribs[4] = EGL_NONE;
#else
        EGLint pi32ConfigAttribs[3];
        pi32ConfigAttribs[0] = EGL_SURFACE_TYPE;
        pi32ConfigAttribs[1] = EGL_WINDOW_BIT;
        pi32ConfigAttribs[2] = EGL_NONE;
#endif

        // Step 5 - Find a config that matches all requirements.
        int iConfigs;
        EGLConfig eglConfig;
        eglChooseConfig(mEglDisplay, pi32ConfigAttribs, &eglConfig, 1,
                        &iConfigs);
        if (iConfigs != 1)
        {
            printf("Error: eglChooseConfig(): config not found \n");
            exit(-1);
        }

        // Step 6 - Create a surface to draw to.

        mEglSurface = eglCreatePbufferSurface(mEglDisplay, eglConfig, NULL);
        // Step 7 - Create a context.

        if (!g_eglContext)
        {
#ifdef CONTEXT_ES20
            g_eglContext = eglCreateContext(mEglDisplay, eglConfig, NULL, ai32ContextAttribs);
#else
            g_eglContext = eglCreateContext(g_eglDisplay, eglConfig, NULL, NULL);

#endif
            mEglContext=g_eglContext;
        }
        else
        {
            #ifdef CONTEXT_ES20
            mEglContext = eglCreateContext(mEglDisplay, eglConfig, g_eglContext, ai32ContextAttribs);
    #else
            g_eglContext = eglCreateContext(g_eglDisplay, eglConfig, NULL, NULL);
        #endif
        }

        // Step 8 - Bind the context to the current thread
        if (eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext) != EGL_TRUE)
        {
            EGLint error = eglGetError();
            printf("eglMakeCurrent fail the erroer is %x\n", error);
            exit(-1);
        }
        // end of standard gl context setup

        // Step 9 - create framebuffer object
        glGenFramebuffers(1, &mFboId);
        glBindFramebuffer(GL_FRAMEBUFFER, mFboId);

        glGenRenderbuffers(1, &mRenderBuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, mRenderBuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA4, mCanvasWidth, mCanvasHeight);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, mRenderBuffer);
        glGenRenderbuffers(1, &mDepthRenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, mDepthRenderbuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, mCanvasWidth, mCanvasHeight);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mDepthRenderbuffer);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mDepthRenderbuffer);

        // check FBO status
        GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
        if (status != GL_FRAMEBUFFER_COMPLETE)
        {
            printf("Problem with OpenGL framebuffer after specifying color render buffer: n%x \n", status);
            exit(-1);
        }
        else
        {
            printf("FBO create success %p, fboId=%d, renderbufferId=%d depthbufferId=%d\n", this, mFboId, mRenderBuffer, mDepthRenderbuffer);
        }

        GLint format = 0, type = 0;
        glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &format);
        glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &type);
        this->initCanvas();
        fboVector.push_back(mFboId);
    }

    void GRenderContext::makeCurrent()
    {
        if (mEglContext != nullptr)
        {
            //判断当前上下文是否是该canvas的上下文
            EGLContext currentContext = eglGetCurrentContext();
            EGLSurface  currentSurface=eglGetCurrentSurface(EGL_DRAW);
            if (mEglContext == currentContext && currentSurface==mEglSurface)
            {
                return;
            }
        }
        if (mEglContext != EGL_NO_CONTEXT && mEglDisplay != EGL_NO_DISPLAY)
        {
            if (eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext) != EGL_TRUE)
            {
                printf("eglMakeCurrent fail \n");
                exit(-1);
            }
        }
        this->BindFBO();
    }

    void GRenderContext::initCanvas()
    {
        mCanvas->CreateContext();
        mCanvas->GetGCanvasContext()->SetClearColor(gcanvas::StrValueToColorRGBA("white"));
        mCanvas->GetGCanvasContext()->ClearScreen();
        mCanvas->GetGCanvasContext()->SetDevicePixelRatio(mRatio);
        mCanvas->OnSurfaceChanged(0, 0, mCanvasWidth, mCanvasHeight);
    }
    void GRenderContext::drawFrame()
    {
        mCanvas->drawFrame();
        this->drawCount++;
    }

    void GRenderContext::render2file(std::string fileName, PIC_FORMAT format)
    {
        int size = 4 * mCanvasWidth * mCanvasHeight;
        unsigned char *inputData = new unsigned char[size];
        if (!inputData)
        {
            printf("Error: allocate inputData memeroy faied! \n");
            return;
        }
        glReadPixels(0, 0, mCanvasWidth, mCanvasHeight, GL_RGBA, GL_UNSIGNED_BYTE, inputData);
        unsigned char *data = new unsigned char[4 * mWidth * mHeight];
        if (!data)
        {
            printf("Error: allocate data memeroy faied! \n");
            delete inputData;
            inputData = nullptr;
            return;
        }

        gcanvas::PixelsSampler(mCanvasWidth, mCanvasHeight, (int *)inputData, mWidth, mHeight, (int *)data);
        gcanvas::FlipPixel(data, mWidth, mHeight);

        delete inputData;
        inputData = nullptr;

        if (format == PNG_FORAMT)
        {
            encodePixelsToPNGFile(fileName + ".png", data, mWidth, mHeight);
        }
        else if (format == JPEG_FORMAT)
        {
            encodePixelsToJPEGFile(fileName + ".jpg", data, mWidth, mHeight);
        }
        delete data;
        data = nullptr;
    }

    void GRenderContext::destoryRenderEnviroment()
    {
        if (this->mFboId != 0)
        {
            glDeleteFramebuffers(1, &this->mFboId);
        }
        if (this->mRenderBuffer != 0)
        {
            glDeleteRenderbuffers(1, &this->mRenderBuffer);
        }
        if (this->mDepthRenderbuffer != 0)
        {
            glDeleteRenderbuffers(1, &this->mDepthRenderbuffer);
        }
        if (this->textures.size() > 0)
        {
            glDeleteTextures(this->textures.size(), (GLuint *)&textures[0]);
        }

        if (mEglSurface != EGL_NO_SURFACE)
        {
            eglDestroySurface(mEglDisplay, mEglSurface);
            mEglSurface = EGL_NO_SURFACE;
        }

        std::vector<GRenderContext *>::iterator iter = find(g_RenderContextVC.begin(), g_RenderContextVC.end(), this);
        if (iter != g_RenderContextVC.end())
        {
            g_RenderContextVC.erase(iter);
        }

        if (g_RenderContextVC.size() <= 0)
        {
            if (mEglDisplay != EGL_NO_DISPLAY)
            {
                eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
                if (mEglContext != EGL_NO_CONTEXT)
                {
                    eglDestroyContext(mEglDisplay, mEglContext);
                }
                eglTerminate(mEglDisplay);
            }

            mEglDisplay = EGL_NO_DISPLAY;
            mEglContext = EGL_NO_CONTEXT;
        }
    }

    void GRenderContext::recordTextures(int textureId)
    {
        this->textures.push_back(textureId);
    }

    void GRenderContext::BindFBO()
    {
        GLint curFBOId = 0;
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &curFBOId);
        if (curFBOId != mFboId)
        {
            glBindFramebuffer(GL_FRAMEBUFFER, mFboId);
            printf("bindfbo value is %d\n", mFboId);
        }
    }

    GRenderContext::~GRenderContext()
    {
        this->destoryRenderEnviroment();
    }
} // namespace NodeBinding
<commit_msg>fix: check the fbo fail<commit_after>#include "GRenderContext.h"
#include <fstream>
#include <cmath>
#include "GFrameBufferObject.h"
#include "GLUtil.h"
#include "Util.h"
#include <EGL/egl.h>
#include <vector>

namespace NodeBinding
{

    static std::vector<GRenderContext *> g_RenderContextVC;
    static EGLContext g_eglContext = nullptr;
    static std::vector<GLuint> fboVector;

    GRenderContext::GRenderContext(int width, int height)
        : mWidth(width), mHeight(height), mRatio(2.0),mEglDisplay(EGL_NO_DISPLAY)
    {
        GCanvasConfig config = {true, false};
        this->mCanvas = std::make_shared<gcanvas::GCanvas>("node-gcanvas", config, nullptr);
        mCanvasWidth = width * mRatio;
        mCanvasHeight = height * mRatio;
    }

    GRenderContext::GRenderContext(int width, int height, int ratio)
        : mWidth(width), mHeight(height), mRatio(ratio),mEglDisplay(EGL_NO_DISPLAY)
    {
        GCanvasConfig config = {true, true};
        this->mCanvas = std::make_shared<gcanvas::GCanvas>("node-gcanvas", config, nullptr);
        mCanvasWidth = width * mRatio;
        mCanvasHeight = height * mRatio;
    }

    void GRenderContext::initRenderEnviroment()
    {
#ifdef CONTEXT_ES20
        EGLint ai32ContextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
#endif

        // Step 1 - Get the default display.
        if (!mEglDisplay)
        {
            mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
            // Step 2 - Initialize EGL.
            eglInitialize(mEglDisplay, 0, 0);
        }

#ifdef CONTEXT_ES20
        // Step 3 - Make OpenGL ES the current API.
        eglBindAPI(EGL_OPENGL_ES_API);

        // Step 4 - Specify the required configuration attributes.
        EGLint pi32ConfigAttribs[5];
        pi32ConfigAttribs[0] = EGL_SURFACE_TYPE;
        pi32ConfigAttribs[1] = EGL_WINDOW_BIT;
        pi32ConfigAttribs[2] = EGL_RENDERABLE_TYPE;
        pi32ConfigAttribs[3] = EGL_OPENGL_ES2_BIT;
        pi32ConfigAttribs[4] = EGL_NONE;
#else
        EGLint pi32ConfigAttribs[3];
        pi32ConfigAttribs[0] = EGL_SURFACE_TYPE;
        pi32ConfigAttribs[1] = EGL_WINDOW_BIT;
        pi32ConfigAttribs[2] = EGL_NONE;
#endif

        // Step 5 - Find a config that matches all requirements.
        int iConfigs;
        EGLConfig eglConfig;
        eglChooseConfig(mEglDisplay, pi32ConfigAttribs, &eglConfig, 1,
                        &iConfigs);
        if (iConfigs != 1)
        {
            printf("Error: eglChooseConfig(): config not found \n");
            exit(-1);
        }

        // Step 6 - Create a surface to draw to.

        mEglSurface = eglCreatePbufferSurface(mEglDisplay, eglConfig, NULL);
        // Step 7 - Create a context.

        if (!g_eglContext)
        {
#ifdef CONTEXT_ES20
            g_eglContext = eglCreateContext(mEglDisplay, eglConfig, NULL, ai32ContextAttribs);
#else
            g_eglContext = eglCreateContext(g_eglDisplay, eglConfig, NULL, NULL);

#endif
            mEglContext=g_eglContext;
        }
        else
        {
            #ifdef CONTEXT_ES20
            mEglContext = eglCreateContext(mEglDisplay, eglConfig, g_eglContext, ai32ContextAttribs);
    #else
            g_eglContext = eglCreateContext(g_eglDisplay, eglConfig, NULL, NULL);
        #endif
        }

        // Step 8 - Bind the context to the current thread
        if (eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext) != EGL_TRUE)
        {
            EGLint error = eglGetError();
            printf("eglMakeCurrent fail the erroer is %x\n", error);
            exit(-1);
        }
        // end of standard gl context setup

        // Step 9 - create framebuffer object
        glGenFramebuffers(1, &mFboId);
        glBindFramebuffer(GL_FRAMEBUFFER, mFboId);

        glGenRenderbuffers(1, &mRenderBuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, mRenderBuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA4, mCanvasWidth, mCanvasHeight);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, mRenderBuffer);
        glGenRenderbuffers(1, &mDepthRenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, mDepthRenderbuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, mCanvasWidth, mCanvasHeight);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mDepthRenderbuffer);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mDepthRenderbuffer);
        printf("the  canvaswidth is %d the canvas hegiht is %d \n",this->mCanvasWidth,this->mCanvasHeight);
        // check FBO status
        GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
        if (status != GL_FRAMEBUFFER_COMPLETE)
        {
            printf("Problem with OpenGL framebuffer after specifying color render buffer: n%x \n", status);
            exit(-1);
        }
        else
        {
            printf("FBO create success %p, fboId=%d, renderbufferId=%d depthbufferId=%d\n", this, mFboId, mRenderBuffer, mDepthRenderbuffer);
        }

        GLint format = 0, type = 0;
        glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &format);
        glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &type);
        this->initCanvas();
        fboVector.push_back(mFboId);
    }

    void GRenderContext::makeCurrent()
    {
        if (mEglContext != nullptr)
        {
            //判断当前上下文是否是该canvas的上下文
            EGLContext currentContext = eglGetCurrentContext();
            EGLSurface  currentSurface=eglGetCurrentSurface(EGL_DRAW);
            if (mEglContext == currentContext && currentSurface==mEglSurface)
            {
                return;
            }
        }
        if (mEglContext != EGL_NO_CONTEXT && mEglDisplay != EGL_NO_DISPLAY)
        {
            if (eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext) != EGL_TRUE)
            {
                printf("eglMakeCurrent fail \n");
                exit(-1);
            }
        }
        this->BindFBO();
    }

    void GRenderContext::initCanvas()
    {
        mCanvas->CreateContext();
        mCanvas->GetGCanvasContext()->SetClearColor(gcanvas::StrValueToColorRGBA("white"));
        mCanvas->GetGCanvasContext()->ClearScreen();
        mCanvas->GetGCanvasContext()->SetDevicePixelRatio(mRatio);
        mCanvas->OnSurfaceChanged(0, 0, mCanvasWidth, mCanvasHeight);
    }
    void GRenderContext::drawFrame()
    {
        mCanvas->drawFrame();
        this->drawCount++;
    }

    void GRenderContext::render2file(std::string fileName, PIC_FORMAT format)
    {
        int size = 4 * mCanvasWidth * mCanvasHeight;
        unsigned char *inputData = new unsigned char[size];
        if (!inputData)
        {
            printf("Error: allocate inputData memeroy faied! \n");
            return;
        }
        glReadPixels(0, 0, mCanvasWidth, mCanvasHeight, GL_RGBA, GL_UNSIGNED_BYTE, inputData);
        unsigned char *data = new unsigned char[4 * mWidth * mHeight];
        if (!data)
        {
            printf("Error: allocate data memeroy faied! \n");
            delete inputData;
            inputData = nullptr;
            return;
        }

        gcanvas::PixelsSampler(mCanvasWidth, mCanvasHeight, (int *)inputData, mWidth, mHeight, (int *)data);
        gcanvas::FlipPixel(data, mWidth, mHeight);

        delete inputData;
        inputData = nullptr;

        if (format == PNG_FORAMT)
        {
            encodePixelsToPNGFile(fileName + ".png", data, mWidth, mHeight);
        }
        else if (format == JPEG_FORMAT)
        {
            encodePixelsToJPEGFile(fileName + ".jpg", data, mWidth, mHeight);
        }
        delete data;
        data = nullptr;
    }

    void GRenderContext::destoryRenderEnviroment()
    {
        if (this->mFboId != 0)
        {
            glDeleteFramebuffers(1, &this->mFboId);
        }
        if (this->mRenderBuffer != 0)
        {
            glDeleteRenderbuffers(1, &this->mRenderBuffer);
        }
        if (this->mDepthRenderbuffer != 0)
        {
            glDeleteRenderbuffers(1, &this->mDepthRenderbuffer);
        }
        if (this->textures.size() > 0)
        {
            glDeleteTextures(this->textures.size(), (GLuint *)&textures[0]);
        }

        if (mEglSurface != EGL_NO_SURFACE)
        {
            eglDestroySurface(mEglDisplay, mEglSurface);
            mEglSurface = EGL_NO_SURFACE;
        }

        std::vector<GRenderContext *>::iterator iter = find(g_RenderContextVC.begin(), g_RenderContextVC.end(), this);
        if (iter != g_RenderContextVC.end())
        {
            g_RenderContextVC.erase(iter);
        }

        if (g_RenderContextVC.size() <= 0)
        {
            if (mEglDisplay != EGL_NO_DISPLAY)
            {
                eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
                if (mEglContext != EGL_NO_CONTEXT)
                {
                    eglDestroyContext(mEglDisplay, mEglContext);
                }
                eglTerminate(mEglDisplay);
            }

            mEglDisplay = EGL_NO_DISPLAY;
            mEglContext = EGL_NO_CONTEXT;
        }
    }

    void GRenderContext::recordTextures(int textureId)
    {
        this->textures.push_back(textureId);
    }

    void GRenderContext::BindFBO()
    {
        GLint curFBOId = 0;
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &curFBOId);
        if (curFBOId != mFboId)
        {
            glBindFramebuffer(GL_FRAMEBUFFER, mFboId);
            printf("bindfbo value is %d\n", mFboId);
        }
    }

    GRenderContext::~GRenderContext()
    {
        this->destoryRenderEnviroment();
    }
} // namespace NodeBinding
<|endoftext|>


<commit_before>#include "doofit/plotting/Plot/Plot.h"

// STL
#include <string>
#include <sstream>
#include <vector>

// boost
#include <boost/regex.hpp>

// ROOT
#include "TIterator.h"

// from RooFit
#include "RooArgList.h"
#include "RooAbsRealLValue.h"
#include "RooAbsData.h"
#include "RooAbsPdf.h"
#include "RooPlot.h"
#include "RooHist.h"
#include "RooBinning.h"

// from Project
#include "doocore/io/MsgStream.h"
#include "doocore/lutils/lutils.h"
#include "doofit/plotting/Plot/PlotConfig.h"

using namespace ROOT;
using namespace RooFit;
using namespace doocore::io;

namespace doofit {
namespace plotting {

Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooArgList& pdfs, const std::string& plot_name)
: config_plot_(cfg_plot),
  dimension_(dimension),
  datasets_(),
  plot_name_(plot_name)
{
  datasets_.push_back(&dataset);
  pdf_ = dynamic_cast<RooAbsPdf*>(pdfs.first());

  if (&dimension_ == NULL) {
    serr << "Plot::Plot(): Dimension is invalid." << endmsg;
    throw 1;
  }
  if (datasets_.front() == NULL) {
    serr << "Plot::Plot(): Dataset is invalid." << endmsg;
    throw 1;
  }
  if (plot_name_ == "") {
    plot_name_ = dimension_.GetName();
  }

  for (int i=1; i<pdfs.getSize(); ++i) {
    RooAbsArg* sub_arg = pdfs.at(i);
    const RooAbsPdf* sub_pdf = dynamic_cast<RooAbsPdf*>(sub_arg);

    if (sub_pdf != NULL) {
      components_.push_back(RooArgSet(*sub_pdf));
    }
  }
}

Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooAbsPdf& pdf, const std::vector<std::string>& components, const std::string& plot_name)
: config_plot_(cfg_plot),
  dimension_(dimension),
  datasets_(),
  plot_name_(plot_name)
{
  datasets_.push_back(&dataset);
  pdf_ = &pdf;

  if (pdf_ == NULL) {
    serr << "Plot::Plot(): Main PDF is invalid." << endmsg;
    throw 1;
  }
  if (&dimension_ == NULL) {
    serr << "Plot::Plot(): Dimension is invalid." << endmsg;
    throw 1;
  }
  if (datasets_.front() == NULL) {
    serr << "Plot::Plot(): Dataset is invalid." << endmsg;
    throw 1;
  }
  if (plot_name_ == "") {
    plot_name_ = dimension_.GetName();
  }

  // iterate over sub PDFs and match supplied regular expressions
  RooArgSet nodes;
  pdf.branchNodeServerList(&nodes);

  for (std::vector<std::string>::const_iterator it = components.begin();
       it != components.end(); ++it) {
    boost::regex r(*it);
    components_.push_back(RooArgSet());

    TIterator* it_nodes = nodes.createIterator();
    RooAbsArg* node = NULL;

    while ((node = dynamic_cast<RooAbsArg*>(it_nodes->Next()))) {
      RooAbsPdf* pdf_node = dynamic_cast<RooAbsPdf*>(node);
      if (pdf_node != NULL) {
        std::string pdf_name = pdf_node->GetName();

        // exclude resolution models generated by RooFit and match the rest
        if (pdf_name.find("_conv_") == -1 && regex_match(pdf_name,r)) {
          components_.back().add(*pdf_node);
        }
      }
    }
    delete it_nodes;
  }
}

void Plot::PlotHandler(ScaleType sc_y, std::string suffix) const {
  if (suffix == "") suffix = "_log";

  std::string plot_name = plot_name_;

  std::stringstream log_plot_name_sstr;
  log_plot_name_sstr << plot_name << suffix;
  std::string log_plot_name = log_plot_name_sstr.str();

  std::stringstream pull_plot_sstr;
  pull_plot_sstr << plot_name << "_pull";
  std::string pull_plot_name = pull_plot_sstr.str();

  std::stringstream log_pull_plot_sstr;
  log_pull_plot_sstr << plot_name << "_pull" << suffix;
  std::string log_pull_plot_name = log_pull_plot_sstr.str();

  sinfo << "Plotting " << dimension_.GetName() << " into " << config_plot_.plot_directory() << plot_name << endmsg;

  doocore::lutils::setStyle("LHCb");

  RooCmdArg range_arg;

  // x range
  if (!dimension_.hasMin() && !dimension_.hasMax()) {
    double min, max;

    // ugly const_cast because RooFit is stupid (RooDataSet::getRange needs non-const RooRealVar)
    RooRealVar* dimension_non_const = const_cast<RooRealVar*>(dynamic_cast<const RooRealVar*>(&dimension_));
    datasets_.front()->getRange(*dimension_non_const, min, max);

    double min_t, max_t;
    for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin()+1;
         it != datasets_.end(); ++it) {
      (*it)->getRange(*dimension_non_const, min_t, max_t);
      if (min_t < min) min = min_t;
      if (max_t > max) max = max_t;
    }

    range_arg = Range(min, max);
  }
  RooPlot* plot_frame = dimension_.frame(range_arg);

  for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
       it != datasets_.end(); ++it) {
    (*it)->plotOn(plot_frame, Binning(dimension_.getBinning())/*, Rescale(1.0/(*it)->sumEntries())*/);
  }

  // y range adaptively for log scale
  RooHist * data = (RooHist*) plot_frame->findObject(0,RooHist::Class());
  double x,y;
  data->GetPoint(0,x,y);
  double min_data_entry = y;
  for (unsigned int i = 1; i < data->GetN(); ++i) {
    data->GetPoint(i,x,y);
    if (min_data_entry > y) min_data_entry = y;
  }
  if (min_data_entry == 0.0) min_data_entry = 1.0;
  double min_plot = TMath::Power(10.0,TMath::Log10(min_data_entry)-0.7);

//  sdebug << "minimum entry in histogram: " << min_data_entry << endmsg;
//  sdebug << "minimum for plot range: " << min_plot << endmsg;

  TLatex label(0.65,0.85,"LHCb");

  config_plot_.OnDemandOpenPlotStack();
  if (pdf_ != NULL) {
    RooPlot* plot_frame_pull = dimension_.frame(range_arg);
    for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
         it != datasets_.end(); ++it) {
      (*it)->plotOn(plot_frame_pull, Binning(dimension_.getBinning()));
    }

    // I feel so stupid doing this but apparently RooFit leaves me no other way...
    RooCmdArg arg1, arg2, arg3, arg4, arg5, arg6, arg7;
    if (plot_args_.size() > 0) arg1 = plot_args_[0];
    if (plot_args_.size() > 1) arg2 = plot_args_[1];
    if (plot_args_.size() > 2) arg3 = plot_args_[2];
    if (plot_args_.size() > 3) arg4 = plot_args_[3];
    if (plot_args_.size() > 4) arg5 = plot_args_[4];
    if (plot_args_.size() > 5) arg6 = plot_args_[5];
    if (plot_args_.size() > 6) arg7 = plot_args_[6];

    int i=1;
    for (std::vector<RooArgSet>::const_iterator it = components_.begin();
         it != components_.end(); ++it) {
      if (it->getSize() > 0) {
        sinfo << "Plotting component " << it->first()->GetName() << endmsg;
        pdf_->plotOn(plot_frame, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
        pdf_->plotOn(plot_frame_pull, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
        ++i;
      }
    }

    pdf_->plotOn(plot_frame, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
    pdf_->plotOn(plot_frame_pull, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);

    // =10^(ln(11)/ln(10)-0.5)
    //plot_frame_pull->SetMinimum(0.5);

    plot_frame_pull->SetMinimum(0.5);
    plot_frame_pull->SetMaximum(1.3*plot_frame_pull->GetMaximum());
    if (sc_y == kLinear || sc_y == kBoth) {
      doocore::lutils::PlotPulls(pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), false, false, true);
      doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), false, false, true, "");
    }

    plot_frame_pull->SetMinimum(min_plot);
    if (sc_y == kLogarithmic || sc_y == kBoth) {
      doocore::lutils::PlotPulls(log_pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), true, false, true);
      doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), true, false, true, "");
    }

    delete plot_frame_pull;
  }

  plot_frame->SetMinimum(0.0);
  plot_frame->SetMaximum(1.3*plot_frame->GetMaximum());
  if (sc_y == kLinear || sc_y == kBoth) {
    doocore::lutils::PlotSimple(plot_name, plot_frame, label, config_plot_.plot_directory(), false);
    doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), false);
  }

  plot_frame->SetMinimum(min_plot);
  if (sc_y == kLogarithmic || sc_y == kBoth) {
    doocore::lutils::PlotSimple(log_plot_name, plot_frame, label, config_plot_.plot_directory(), true);
    doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), true);
  }

  delete plot_frame;
}

Plot::~Plot() {}

} // namespace plotting
} // namespace doofit
<commit_msg>Plotting: adding y range debug output<commit_after>#include "doofit/plotting/Plot/Plot.h"

// STL
#include <string>
#include <sstream>
#include <vector>

// boost
#include <boost/regex.hpp>

// ROOT
#include "TIterator.h"

// from RooFit
#include "RooArgList.h"
#include "RooAbsRealLValue.h"
#include "RooAbsData.h"
#include "RooAbsPdf.h"
#include "RooPlot.h"
#include "RooHist.h"
#include "RooBinning.h"

// from Project
#include "doocore/io/MsgStream.h"
#include "doocore/lutils/lutils.h"
#include "doofit/plotting/Plot/PlotConfig.h"

using namespace ROOT;
using namespace RooFit;
using namespace doocore::io;

namespace doofit {
namespace plotting {

Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooArgList& pdfs, const std::string& plot_name)
: config_plot_(cfg_plot),
  dimension_(dimension),
  datasets_(),
  plot_name_(plot_name)
{
  datasets_.push_back(&dataset);
  pdf_ = dynamic_cast<RooAbsPdf*>(pdfs.first());

  if (&dimension_ == NULL) {
    serr << "Plot::Plot(): Dimension is invalid." << endmsg;
    throw 1;
  }
  if (datasets_.front() == NULL) {
    serr << "Plot::Plot(): Dataset is invalid." << endmsg;
    throw 1;
  }
  if (plot_name_ == "") {
    plot_name_ = dimension_.GetName();
  }

  for (int i=1; i<pdfs.getSize(); ++i) {
    RooAbsArg* sub_arg = pdfs.at(i);
    const RooAbsPdf* sub_pdf = dynamic_cast<RooAbsPdf*>(sub_arg);

    if (sub_pdf != NULL) {
      components_.push_back(RooArgSet(*sub_pdf));
    }
  }
}

Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooAbsPdf& pdf, const std::vector<std::string>& components, const std::string& plot_name)
: config_plot_(cfg_plot),
  dimension_(dimension),
  datasets_(),
  plot_name_(plot_name)
{
  datasets_.push_back(&dataset);
  pdf_ = &pdf;

  if (pdf_ == NULL) {
    serr << "Plot::Plot(): Main PDF is invalid." << endmsg;
    throw 1;
  }
  if (&dimension_ == NULL) {
    serr << "Plot::Plot(): Dimension is invalid." << endmsg;
    throw 1;
  }
  if (datasets_.front() == NULL) {
    serr << "Plot::Plot(): Dataset is invalid." << endmsg;
    throw 1;
  }
  if (plot_name_ == "") {
    plot_name_ = dimension_.GetName();
  }

  // iterate over sub PDFs and match supplied regular expressions
  RooArgSet nodes;
  pdf.branchNodeServerList(&nodes);

  for (std::vector<std::string>::const_iterator it = components.begin();
       it != components.end(); ++it) {
    boost::regex r(*it);
    components_.push_back(RooArgSet());

    TIterator* it_nodes = nodes.createIterator();
    RooAbsArg* node = NULL;

    while ((node = dynamic_cast<RooAbsArg*>(it_nodes->Next()))) {
      RooAbsPdf* pdf_node = dynamic_cast<RooAbsPdf*>(node);
      if (pdf_node != NULL) {
        std::string pdf_name = pdf_node->GetName();

        // exclude resolution models generated by RooFit and match the rest
        if (pdf_name.find("_conv_") == -1 && regex_match(pdf_name,r)) {
          components_.back().add(*pdf_node);
        }
      }
    }
    delete it_nodes;
  }
}

void Plot::PlotHandler(ScaleType sc_y, std::string suffix) const {
  if (suffix == "") suffix = "_log";

  std::string plot_name = plot_name_;

  std::stringstream log_plot_name_sstr;
  log_plot_name_sstr << plot_name << suffix;
  std::string log_plot_name = log_plot_name_sstr.str();

  std::stringstream pull_plot_sstr;
  pull_plot_sstr << plot_name << "_pull";
  std::string pull_plot_name = pull_plot_sstr.str();

  std::stringstream log_pull_plot_sstr;
  log_pull_plot_sstr << plot_name << "_pull" << suffix;
  std::string log_pull_plot_name = log_pull_plot_sstr.str();

  sinfo << "Plotting " << dimension_.GetName() << " into " << config_plot_.plot_directory() << plot_name << endmsg;

  doocore::lutils::setStyle("LHCb");

  RooCmdArg range_arg;

  // x range
  if (!dimension_.hasMin() && !dimension_.hasMax()) {
    double min, max;

    // ugly const_cast because RooFit is stupid (RooDataSet::getRange needs non-const RooRealVar)
    RooRealVar* dimension_non_const = const_cast<RooRealVar*>(dynamic_cast<const RooRealVar*>(&dimension_));
    datasets_.front()->getRange(*dimension_non_const, min, max);

    double min_t, max_t;
    for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin()+1;
         it != datasets_.end(); ++it) {
      (*it)->getRange(*dimension_non_const, min_t, max_t);
      if (min_t < min) min = min_t;
      if (max_t > max) max = max_t;
    }

    range_arg = Range(min, max);
  }
  RooPlot* plot_frame = dimension_.frame(range_arg);

  for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
       it != datasets_.end(); ++it) {
    (*it)->plotOn(plot_frame, Binning(dimension_.getBinning())/*, Rescale(1.0/(*it)->sumEntries())*/);
  }

  // y range adaptively for log scale
  RooHist * data = (RooHist*) plot_frame->findObject(0,RooHist::Class());
  double x,y;
  data->GetPoint(0,x,y);
  double min_data_entry = y;
  for (unsigned int i = 1; i < data->GetN(); ++i) {
    data->GetPoint(i,x,y);
    if (min_data_entry > y) min_data_entry = y;
  }
  if (min_data_entry == 0.0) min_data_entry = 1.0;
  double min_plot = TMath::Power(10.0,TMath::Log10(min_data_entry)-0.7);

//  sdebug << "minimum entry in histogram: " << min_data_entry << endmsg;
//  sdebug << "minimum for plot range: " << min_plot << endmsg;

  TLatex label(0.65,0.85,"LHCb");

  config_plot_.OnDemandOpenPlotStack();
  if (pdf_ != NULL) {
    RooPlot* plot_frame_pull = dimension_.frame(range_arg);

    // I feel so stupid doing this but apparently RooFit leaves me no other way...
    RooCmdArg arg1, arg2, arg3, arg4, arg5, arg6, arg7;
    if (plot_args_.size() > 0) arg1 = plot_args_[0];
    if (plot_args_.size() > 1) arg2 = plot_args_[1];
    if (plot_args_.size() > 2) arg3 = plot_args_[2];
    if (plot_args_.size() > 3) arg4 = plot_args_[3];
    if (plot_args_.size() > 4) arg5 = plot_args_[4];
    if (plot_args_.size() > 5) arg6 = plot_args_[5];
    if (plot_args_.size() > 6) arg7 = plot_args_[6];

    for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
         it != datasets_.end(); ++it) {
      (*it)->plotOn(plot_frame_pull, Binning(dimension_.getBinning()));
    }

    int i=1;
    for (std::vector<RooArgSet>::const_iterator it = components_.begin();
         it != components_.end(); ++it) {
      if (it->getSize() > 0) {
        sinfo << "Plotting component " << it->first()->GetName() << endmsg;
        pdf_->plotOn(plot_frame, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
        pdf_->plotOn(plot_frame_pull, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
        ++i;
      }
    }

    pdf_->plotOn(plot_frame, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
    pdf_->plotOn(plot_frame_pull, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);

    // =10^(ln(11)/ln(10)-0.5)
    //plot_frame_pull->SetMinimum(0.5);

    plot_frame_pull->SetMinimum(0.5);
    plot_frame_pull->SetMaximum(1.3*plot_frame_pull->GetMaximum());
    if (sc_y == kLinear || sc_y == kBoth) {
      doocore::lutils::PlotPulls(pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), false, false, true);
      doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), false, false, true, "");
    }

    sdebug << "Plot y axis minimum for log scale plot: " << min_plot << endmsg;
    plot_frame_pull->SetMinimum(min_plot);
    if (sc_y == kLogarithmic || sc_y == kBoth) {
      doocore::lutils::PlotPulls(log_pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), true, false, true);
      doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), true, false, true, "");
    }

    delete plot_frame_pull;
  }

  plot_frame->SetMinimum(0.0);
  plot_frame->SetMaximum(1.3*plot_frame->GetMaximum());
  if (sc_y == kLinear || sc_y == kBoth) {
    doocore::lutils::PlotSimple(plot_name, plot_frame, label, config_plot_.plot_directory(), false);
    doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), false);
  }

  plot_frame->SetMinimum(min_plot);
  if (sc_y == kLogarithmic || sc_y == kBoth) {
    doocore::lutils::PlotSimple(log_plot_name, plot_frame, label, config_plot_.plot_directory(), true);
    doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), true);
  }

  delete plot_frame;
}

Plot::~Plot() {}

} // namespace plotting
} // namespace doofit
<|endoftext|>


<commit_before>
#include <libclientserver.h>

PerfCounter::PerfCounter(const std::string Key)
{
	m_Key = Key;
	if (clock_gettime(CLOCK_MONOTONIC, &m_starttime) < 0)
		abort();
	printf("Start: %s\n", Key.c_str());
}

PerfCounter::~PerfCounter()
{
	struct timespec endtime;
	struct timespec diff;

	if (clock_gettime(CLOCK_MONOTONIC, &endtime) < 0)
		abort();

	Time::Diff(&m_starttime, &endtime, &diff);

	PerfManager::UpdateCounter(m_Key, &diff);
	printf("End: %s\n", m_Key.c_str());
}

<commit_msg>Remove Some Debug printf's<commit_after>
#include <libclientserver.h>

PerfCounter::PerfCounter(const std::string Key)
{
	m_Key = Key;
	if (clock_gettime(CLOCK_MONOTONIC, &m_starttime) < 0)
		abort();
}

PerfCounter::~PerfCounter()
{
	struct timespec endtime;
	struct timespec diff;

	if (clock_gettime(CLOCK_MONOTONIC, &endtime) < 0)
		abort();

	Time::Diff(&m_starttime, &endtime, &diff);

	PerfManager::UpdateCounter(m_Key, &diff);
}

<|endoftext|>


<commit_before>// $Id: $
//==========================================================================
//  AIDA Detector description implementation for LCD
//--------------------------------------------------------------------------
// Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
// All rights reserved.
//
// For the licensing terms see $DD4hepINSTALL/LICENSE.
// For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
//
// Author     : M.Frank
// Modified by: D.Protopopescu
// Includes extensions as implemented by N. Nikiforou in TrackerEndcap_o2_v04_geo.cpp
//
//==========================================================================
//
// Specialized generic detector constructor
//
//==========================================================================
#include "DD4hep/DetFactoryHelper.h"
#include "XML/Utilities.h"
#include <map>
#include "DDRec/DetectorData.h"

using namespace std;
using namespace DD4hep;
using namespace DD4hep::Geometry;

static Ref_t create_detector(LCDD& lcdd, xml_h e, SensitiveDetector sens)  {
  typedef vector<PlacedVolume> Placements;
  xml_det_t   x_det     = e;
  Material    vacuum    = lcdd.vacuum();
  int         det_id    = x_det.id();
  string      det_name  = x_det.nameStr();
  bool        reflect   = x_det.reflect(false);
  DetElement  sdet        (det_name,det_id);
  int         m_id=0, c_id=0, n_sensor=0;
  map<string,Volume> modules;
  map<string, Placements>  sensitives;
  PlacedVolume pv;

  // --- create an envelope volume and position it into the world ---------------------

  Volume envelope = XML::createPlacedEnvelope( lcdd,  e , sdet ) ;
  XML::setDetectorTypeFlag( e, sdet ) ;

  if( lcdd.buildType() == BUILD_ENVELOPE ) return sdet ;

  //-----------------------------------------------------------------------------------

  DDRec::ZDiskPetalsData*  zDiskPetalsData = new DDRec::ZDiskPetalsData ;

  envelope.setVisAttributes(lcdd.invisible());
  sens.setType("tracker");

  for(xml_coll_t mi(x_det,_U(module)); mi; ++mi, ++m_id)  {
    xml_comp_t x_mod   = mi;
    string     m_nam   = x_mod.nameStr();
    xml_comp_t trd     = x_mod.trd();
    double     posY;
    double     x1      = trd.x1();
    double     x2      = trd.x2();
    double     z       = trd.z();
    double     y1, y2, total_thickness=0.;
    xml_coll_t ci(x_mod,_U(module_component));
    for(ci.reset(), total_thickness=0.0; ci; ++ci)
      total_thickness += xml_comp_t(ci).thickness();

    y1 = y2 = total_thickness / 2;
    Volume  m_volume(m_nam, Trapezoid(x1, x2, y1, y2, z), vacuum);
    m_volume.setVisAttributes(lcdd.visAttributes(x_mod.visStr()));

    // Loop over slices
    // The first slice (top in the xml) is placed at the "bottom" of the module
    for(ci.reset(), n_sensor=1, c_id=0, posY=-y1; ci; ++ci, ++c_id)  {
      xml_comp_t c       = ci;
      double     c_thick = c.thickness();
      Material   c_mat   = lcdd.material(c.materialStr());
      string     c_name  = _toString(c_id,"component%d");
      Volume     c_vol(c_name, Trapezoid(x1,x2,c_thick/2e0,c_thick/2e0,z), c_mat);

      c_vol.setVisAttributes(lcdd.visAttributes(c.visStr()));
      pv = m_volume.placeVolume(c_vol,Position(0,posY+c_thick/2,0));
      if ( c.isSensitive() ) {
        c_vol.setSensitiveDetector(sens);
        sensitives[m_nam].push_back(pv);
        ++n_sensor;
      }
      posY += c_thick;
    }
    modules[m_nam] = m_volume;
  }

  for(xml_coll_t li(x_det,_U(layer)); li; ++li)  {
    xml_comp_t  x_layer(li);
    int l_id    = x_layer.id();
    int mod_num = 0;
    int ring_num = 0;

    double sumZ(0.), innerR(1e100), outerR(0.);

    for(xml_coll_t ri(x_layer,_U(ring)); ri; ++ri)  {
      xml_comp_t x_ring = ri;
      double r        = x_ring.r();
      double phi0     = x_ring.phi0(0);
      double zstart   = x_ring.zstart();
      double dz       = x_ring.dz(0);
      int    nmodules = x_ring.nmodules();
      string m_nam    = x_ring.moduleStr();
      Volume m_vol    = modules[m_nam];
      double iphi     = 2*M_PI/nmodules;
      double phi      = phi0;
      Placements& sensVols = sensitives[m_nam];

      DD4hep::Geometry::Box mod_shape(m_vol.solid());
      if(r - mod_shape->GetDZ()<innerR)
	innerR = r - mod_shape->GetDZ();
      if(r + mod_shape->GetDZ()>outerR)
	outerR = r + mod_shape->GetDZ();
      sumZ += zstart;
      r = r + mod_shape->GetDY();

      for(int k=0; k<nmodules; ++k) {
        string m_base = _toString(l_id,"layer%d") + _toString(mod_num,"_module%d") + _toString(k,"_sensor%d");
        double x = -r*std::cos(phi);
        double y = -r*std::sin(phi);
        DetElement module(sdet,m_base+"_pos",det_id);
        pv = envelope.placeVolume(m_vol,Transform3D(RotationZYX(0,-M_PI/2-phi,-M_PI/2),Position(x,y,zstart+dz)));
        pv.addPhysVolID("side",1).addPhysVolID("layer", l_id).addPhysVolID("module",mod_num).addPhysVolID("sensor",k);
        module.setPlacement(pv);
        for(size_t ic=0; ic<sensVols.size(); ++ic)  {
          PlacedVolume sens_pv = sensVols[ic];
          DetElement comp_elt(module,sens_pv.volume().name(),mod_num);
          comp_elt.setPlacement(sens_pv);
        }

        if ( reflect ) {
          pv = envelope.placeVolume(m_vol,Transform3D(RotationZYX(M_PI,-M_PI/2-phi,-M_PI/2),Position(x,y,-zstart-dz)));
          pv.addPhysVolID("side",-1).addPhysVolID("layer",l_id).addPhysVolID("module",mod_num).addPhysVolID("sensor",k);
          DetElement r_module(sdet,m_base+"_neg",det_id);
          r_module.setPlacement(pv);
          for(size_t ic=0; ic<sensVols.size(); ++ic)  {
            PlacedVolume sens_pv = sensVols[ic];
            DetElement comp_elt(r_module,sens_pv.volume().name(),mod_num);
            comp_elt.setPlacement(sens_pv);
          }
        }
        dz   = -dz;
        phi += iphi;
      }
      ++mod_num;
      ++ring_num;
    }

    DDRec::ZDiskPetalsData::LayerLayout thisLayer ;

    // Only filling what is needed for CED/DDMarlinPandora
    thisLayer.zPosition = sumZ/ring_num; // average z
    thisLayer.distanceSensitive = innerR;
    thisLayer.lengthSensitive = outerR - innerR;
    thisLayer.petalNumber = ring_num; // number of rings in petalNumber, needed for tracking
    zDiskPetalsData->layers.push_back(thisLayer);

  }

  sdet.addExtension< DDRec::ZDiskPetalsData >( zDiskPetalsData ) ;

  return sdet;
}

DECLARE_DETELEMENT(SiTrackerEndcap_o2_v01ext,create_detector)
<commit_msg>Aidan's fixes<commit_after>// $Id: $
//==========================================================================
//  AIDA Detector description implementation for LCD
//--------------------------------------------------------------------------
// Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
// All rights reserved.
//
// For the licensing terms see $DD4hepINSTALL/LICENSE.
// For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
//
// Author     : M.Frank
// Modified by: D.Protopopescu
// Includes extensions as implemented by N. Nikiforou in TrackerEndcap_o2_v04_geo.cpp
//
//==========================================================================
//
// Specialized generic detector constructor
//
//==========================================================================
#include "DD4hep/DetFactoryHelper.h"
#include "XML/Utilities.h"
#include <map>
#include "DDRec/DetectorData.h"

using namespace std;
using namespace DD4hep;
using namespace DD4hep::Geometry;

static Ref_t create_detector(LCDD& lcdd, xml_h e, SensitiveDetector sens)  {
  typedef vector<PlacedVolume> Placements;
  xml_det_t   x_det     = e;
  Material    vacuum    = lcdd.vacuum();
  int         det_id    = x_det.id();
  string      det_name  = x_det.nameStr();
  bool        reflect   = x_det.reflect(false);
  DetElement  sdet        (det_name,det_id);
  int         m_id=0, c_id=0, n_sensor=0;
  map<string,Volume> modules;
  map<string, Placements>  sensitives;
  PlacedVolume pv;

  // --- create an envelope volume and position it into the world ---------------------

  Volume envelope = XML::createPlacedEnvelope( lcdd,  e , sdet ) ;
  XML::setDetectorTypeFlag( e, sdet ) ;

  if( lcdd.buildType() == BUILD_ENVELOPE ) return sdet ;

  //-----------------------------------------------------------------------------------

  DDRec::ZDiskPetalsData*  zDiskPetalsData = new DDRec::ZDiskPetalsData ;

  envelope.setVisAttributes(lcdd.invisible());
  sens.setType("tracker");

  for(xml_coll_t mi(x_det,_U(module)); mi; ++mi, ++m_id)  {
    xml_comp_t x_mod   = mi;
    string     m_nam   = x_mod.nameStr();
    xml_comp_t trd     = x_mod.trd();
    double     posY;
    double     x1      = trd.x1();
    double     x2      = trd.x2();
    double     z       = trd.z();
    double     y1, y2, total_thickness=0.;
    xml_coll_t ci(x_mod,_U(module_component));
    for(ci.reset(), total_thickness=0.0; ci; ++ci)
      total_thickness += xml_comp_t(ci).thickness();

    y1 = y2 = total_thickness / 2;
    Volume  m_volume(m_nam, Trapezoid(x1, x2, y1, y2, z), vacuum);
    m_volume.setVisAttributes(lcdd.visAttributes(x_mod.visStr()));

    // Loop over slices
    // The first slice (top in the xml) is placed at the "bottom" of the module
    for(ci.reset(), n_sensor=1, c_id=0, posY=-y1; ci; ++ci, ++c_id)  {
      xml_comp_t c       = ci;
      double     c_thick = c.thickness();
      Material   c_mat   = lcdd.material(c.materialStr());
      string     c_name  = _toString(c_id,"component%d");
      Volume     c_vol(c_name, Trapezoid(x1,x2,c_thick/2e0,c_thick/2e0,z), c_mat);

      c_vol.setVisAttributes(lcdd.visAttributes(c.visStr()));
      pv = m_volume.placeVolume(c_vol,Position(0,posY+c_thick/2,0));
      if ( c.isSensitive() ) {
        c_vol.setSensitiveDetector(sens);
        sensitives[m_nam].push_back(pv);
        ++n_sensor;
      }
      posY += c_thick;
    }
    modules[m_nam] = m_volume;
  }

  for(xml_coll_t li(x_det,_U(layer)); li; ++li)  {
    xml_comp_t  x_layer(li);
    int l_id    = x_layer.id();
    int mod_num = 0;
    int ring_num = 0;

    double sumZ(0.), innerR(1e100), outerR(0.);

    for(xml_coll_t ri(x_layer,_U(ring)); ri; ++ri)  {
      xml_comp_t x_ring = ri;
      double r        = x_ring.r();
      double phi0     = x_ring.phi0(0);
      double zstart   = x_ring.zstart();
      double dz       = x_ring.dz(0);
      int    nmodules = x_ring.nmodules();
      string m_nam    = x_ring.moduleStr();
      Volume m_vol    = modules[m_nam];
      double iphi     = 2*M_PI/nmodules;
      double phi      = phi0;
      Placements& sensVols = sensitives[m_nam];

      DD4hep::Geometry::Box mod_shape(m_vol.solid());
      if(r - mod_shape->GetDZ()<innerR)
	innerR = r - mod_shape->GetDZ();
      if(r + mod_shape->GetDZ()>outerR)
	outerR = r + mod_shape->GetDZ();
      sumZ += zstart;
      r = r + mod_shape->GetDY();

      for(int k=0; k<nmodules; ++k) {
        string m_base = _toString(l_id,"layer%d") + _toString(mod_num,"_module%d") + _toString(k,"_sensor%d");
        double x = -r*std::cos(phi);
        double y = -r*std::sin(phi);
        DetElement module(sdet,m_base+"_pos",det_id);
        pv = envelope.placeVolume(m_vol,Transform3D(RotationZYX(0,-M_PI/2-phi,-M_PI/2),Position(x,y,zstart+dz)));
        pv.addPhysVolID("side",1).addPhysVolID("layer", l_id).addPhysVolID("module",mod_num).addPhysVolID("sensor",k);
        module.setPlacement(pv);
        for(size_t ic=0; ic<sensVols.size(); ++ic)  {
          PlacedVolume sens_pv = sensVols[ic];
          DetElement comp_elt(module,sens_pv.volume().name(),mod_num);
          comp_elt.setPlacement(sens_pv);
        }

        if ( reflect ) {
          pv = envelope.placeVolume(m_vol,Transform3D(RotationZYX(M_PI,-M_PI/2-phi,-M_PI/2),Position(x,y,-zstart-dz)));
          pv.addPhysVolID("side",-1).addPhysVolID("layer",l_id).addPhysVolID("module",mod_num).addPhysVolID("sensor",k);
          DetElement r_module(sdet,m_base+"_neg",det_id);
          r_module.setPlacement(pv);
          for(size_t ic=0; ic<sensVols.size(); ++ic)  {
            PlacedVolume sens_pv = sensVols[ic];
            DetElement comp_elt(r_module,sens_pv.volume().name(),mod_num);
            comp_elt.setPlacement(sens_pv);
          }
        }
        dz   = -dz;
        phi += iphi;
      }
      ++mod_num;
      ++ring_num;
    }

    DDRec::ZDiskPetalsData::LayerLayout thisLayer ;

    // Only filling what is needed for CED/DDMarlinPandora
    thisLayer.zPosition = sumZ/ring_num; // average z
    thisLayer.distanceSensitive = innerR;
    thisLayer.lengthSensitive = outerR - innerR;
    thisLayer.petalNumber = ring_num; // number of rings in petalNumber, needed for tracking
    zDiskPetalsData->layers.push_back(thisLayer);

  }

  sdet.setAttributes(lcdd,envelope,x_det.regionStr(),x_det.limitsStr(),x_det.visStr());
  sdet.addExtension< DDRec::ZDiskPetalsData >( zDiskPetalsData ) ;

  return sdet;
}

DECLARE_DETELEMENT(SiTrackerEndcap_o2_v01ext,create_detector)
<|endoftext|>


<commit_before>//
// Copyright (c) 2008-2020 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/GraphicsEvents.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Texture2D.h>
#include <Urho3D/Graphics/Zone.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/CheckBox.h>
#include <Urho3D/UI/DropDownList.h>
#include <Urho3D/UI/LineEdit.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/ToolTip.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/UI/Window.h>

#include "WindowSettingsDemo.h"

#include <Urho3D/DebugNew.h>

URHO3D_DEFINE_APPLICATION_MAIN(WindowSettingsDemo)

WindowSettingsDemo::WindowSettingsDemo(Context* context)
    : Sample(context)
    , uiRoot_(GetSubsystem<UI>()->GetRoot())
{
}

void WindowSettingsDemo::Start()
{
    // Execute base class startup
    Sample::Start();

    // Enable OS cursor
    GetSubsystem<Input>()->SetMouseVisible(true);

    // Load XML file containing default UI style sheet
    auto* cache = GetSubsystem<ResourceCache>();
    auto* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");

    // Set the loaded style as default style
    uiRoot_->SetDefaultStyle(style);

    // Create window with settings.
    InitSettings();
    SynchronizeSettings();
    SubscribeToEvent(E_SCREENMODE,
        [this](StringHash /*eventType*/, const VariantMap& /*eventData*/)
    {
        SynchronizeSettings();
    });

    // Set the mouse mode to use in the sample
    Sample::InitMouseMode(MM_FREE);

    // Create scene
    CreateScene();

    // Setup viewport
    auto* renderer = GetSubsystem<Renderer>();
    SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
    renderer->SetViewport(0, viewport);
}

void WindowSettingsDemo::CreateScene()
{
    auto* cache = GetSubsystem<ResourceCache>();

    scene_ = new Scene(context_);
    scene_->CreateComponent<Octree>();

    auto* zone = scene_->CreateComponent<Zone>();
    zone->SetAmbientColor(Color::WHITE);

    // Create 3D object
    Node* objectNode = scene_->CreateChild("Object");
    objectNode->SetRotation(Quaternion(45.0f, 45.0f, 45.0f));
    auto* objectModel = objectNode->CreateComponent<StaticModel>();
    objectModel->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
    objectModel->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));

    // Create camera
    cameraNode_ = scene_->CreateChild("Camera");
    cameraNode_->CreateComponent<Camera>();
    cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -4.0f));

    // Rotate object
    SubscribeToEvent(scene_, E_SCENEUPDATE,
        [objectNode](StringHash /*eventType*/, VariantMap& eventData)
    {
        const float timeStep = eventData[SceneUpdate::P_TIMESTEP].GetFloat();
        objectNode->Rotate(Quaternion(0.0f, 20.0f * timeStep, 0.0f), TS_WORLD);
    });
}

void WindowSettingsDemo::InitSettings()
{
    auto* graphics = GetSubsystem<Graphics>();

    // Create the Window and add it to the UI's root node
    window_ = uiRoot_->CreateChild<Window>("Window");

    // Set Window size and layout settings
    window_->SetPosition(128, 128);
    window_->SetMinWidth(300);
    window_->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6));
    window_->SetMovable(true);
    window_->SetStyleAuto();

    // Create the Window title Text
    auto* windowTitle = window_->CreateChild<Text>("WindowTitle");
    windowTitle->SetText("Window Settings");
    windowTitle->SetStyleAuto();

    // Create monitor selector
    monitorControl_ = window_->CreateChild<DropDownList>("Monitor");
    monitorControl_->SetMinHeight(24);
    monitorControl_->SetStyleAuto();
    for (int i = 0; i < graphics->GetMonitorCount(); ++i)
    {
        auto* text = MakeShared<Text>(context_);
        text->SetText(ToString("Monitor %d", i));
        text->SetMinWidth(CeilToInt(text->GetRowWidth(0) + 10));
        monitorControl_->AddItem(text);
        text->SetStyleAuto();
    }

    // Create resolution selector
    resolutionControl_ = window_->CreateChild<DropDownList>("Resolution");
    resolutionControl_->SetMinHeight(24);
    resolutionControl_->SetStyleAuto();

    auto* resolutionPlaceholder = MakeShared<Text>(context_);
    resolutionPlaceholder->SetText("[Cannot fill list of resolutions]");
    resolutionPlaceholder->SetMinWidth(CeilToInt(resolutionPlaceholder->GetRowWidth(0) + 10));
    resolutionControl_->AddItem(resolutionPlaceholder);
    resolutionPlaceholder->SetStyleAuto();

    // Create fullscreen controller
    auto* fullscreenFrame = window_->CreateChild<UIElement>("Fullscreen Frame");
    fullscreenFrame->SetMinHeight(24);
    fullscreenFrame->SetLayout(LM_HORIZONTAL, 6);

    fullscreenControl_ = fullscreenFrame->CreateChild<CheckBox>("Fullscreen Control");
    fullscreenControl_->SetStyleAuto();

    auto* fullscreenText = fullscreenFrame->CreateChild<Text>("Fullscreen Label");
    fullscreenText->SetText("Fullscreen");
    fullscreenText->SetMinWidth(CeilToInt(fullscreenText->GetRowWidth(0) + 10));
    fullscreenText->SetStyleAuto();

    // Create borderless controller
    auto* borderlessFrame = window_->CreateChild<UIElement>("Borderless Frame");
    borderlessFrame->SetMinHeight(24);
    borderlessFrame->SetLayout(LM_HORIZONTAL, 6);

    borderlessControl_ = borderlessFrame->CreateChild<CheckBox>("Borderless Control");
    borderlessControl_->SetStyleAuto();

    auto* borderlessText = borderlessFrame->CreateChild<Text>("Borderless Label");
    borderlessText->SetText("Borderless");
    borderlessText->SetMinWidth(CeilToInt(borderlessText->GetRowWidth(0) + 10));
    borderlessText->SetStyleAuto();

    // Create resizable controller
    auto* resizableFrame = window_->CreateChild<UIElement>("Resizable Frame");
    resizableFrame->SetMinHeight(24);
    resizableFrame->SetLayout(LM_HORIZONTAL, 6);

    resizableControl_ = resizableFrame->CreateChild<CheckBox>("Resizable Control");
    resizableControl_->SetStyleAuto();

    auto* resizableText = resizableFrame->CreateChild<Text>("Resizable Label");
    resizableText->SetText("Resizable");
    resizableText->SetMinWidth(CeilToInt(resizableText->GetRowWidth(0) + 10));
    resizableText->SetStyleAuto();

    // Create resizable controller
    auto* vsyncFrame = window_->CreateChild<UIElement>("V-Sync Frame");
    vsyncFrame->SetMinHeight(24);
    vsyncFrame->SetLayout(LM_HORIZONTAL, 6);

    vsyncControl_ = vsyncFrame->CreateChild<CheckBox>("V-Sync Control");
    vsyncControl_->SetStyleAuto();

    auto* vsyncText = vsyncFrame->CreateChild<Text>("V-Sync Label");
    vsyncText->SetText("V-Sync");
    vsyncText->SetMinWidth(CeilToInt(vsyncText->GetRowWidth(0) + 10));
    vsyncText->SetStyleAuto();

    // Create multi-sample controller from 1 (= 2^0) to 16 (= 2^4)
    multiSampleControl_ = window_->CreateChild<DropDownList>("Multi-Sample Control");
    multiSampleControl_->SetMinHeight(24);
    multiSampleControl_->SetStyleAuto();
    for (int i = 0; i <= 4; ++i)
    {
        auto* text = MakeShared<Text>(context_);
        text->SetText(i == 0 ? "No MSAA" : ToString("MSAA x%d", 1 << i));
        text->SetMinWidth(CeilToInt(text->GetRowWidth(0) + 10));
        multiSampleControl_->AddItem(text);
        text->SetStyleAuto();
    }

    // Create "Apply" button
    auto* applyButton = window_->CreateChild<Button>("Apply");
    applyButton->SetLayout(LM_HORIZONTAL, 6, IntRect(6, 6, 6, 6));
    applyButton->SetStyleAuto();

    auto* applyButtonText = applyButton->CreateChild<Text>("Apply Text");
    applyButtonText->SetAlignment(HA_CENTER, VA_CENTER);
    applyButtonText->SetText("Apply");
    applyButtonText->SetStyleAuto();

    applyButton->SetFixedWidth(CeilToInt(applyButtonText->GetRowWidth(0) + 20));
    applyButton->SetFixedHeight(30);

    // Apply settings when "Apply" button is clicked
    SubscribeToEvent(applyButton, E_RELEASED,
        [this, graphics](StringHash /*eventType*/, const VariantMap& /*eventData*/)
    {
        const unsigned monitor = monitorControl_->GetSelection();
        if (monitor == M_MAX_UNSIGNED)
            return;

        const auto& resolutions = graphics->GetResolutions(monitor);
        const unsigned selectedResolution = resolutionControl_->GetSelection();
        if (selectedResolution >= resolutions.Size())
            return;

        const bool fullscreen = fullscreenControl_->IsChecked();
        const bool borderless = borderlessControl_->IsChecked();
        const bool resizable = resizableControl_->IsChecked();
        const bool vsync = vsyncControl_->IsChecked();

        const unsigned multiSampleSelection = multiSampleControl_->GetSelection();
        const int multiSample = multiSampleSelection == M_MAX_UNSIGNED ? 1 : static_cast<int>(1 << multiSampleSelection);

        // TODO: Expose these options too?
        const bool highDPI = graphics->GetHighDPI();
        const bool tripleBuffer = graphics->GetTripleBuffer();

        const int width = resolutions[selectedResolution].x_;
        const int height = resolutions[selectedResolution].y_;
        const int refreshRate = resolutions[selectedResolution].z_;
        graphics->SetMode(width, height, fullscreen, borderless, resizable, highDPI, vsync, tripleBuffer, multiSample, monitor, refreshRate);
    });
}

void WindowSettingsDemo::SynchronizeSettings()
{
    auto* graphics = GetSubsystem<Graphics>();

    // Synchronize monitor
    const unsigned currentMonitor = graphics->GetMonitor();
    monitorControl_->SetSelection(currentMonitor);

    // Synchronize resolution list
    resolutionControl_->RemoveAllItems();
    const auto& resolutions = graphics->GetResolutions(currentMonitor);
    for (const IntVector3& resolutions : resolutions)
    {
        auto resolutionEntry = MakeShared<Text>(context_);
        resolutionEntry->SetText(ToString("%dx%d, %d Hz", resolutions.x_, resolutions.y_, resolutions.z_));
        resolutionEntry->SetMinWidth(CeilToInt(resolutionEntry->GetRowWidth(0) + 10));
        resolutionControl_->AddItem(resolutionEntry);
        resolutionEntry->SetStyleAuto();
    }

    // Synchronize selected resolution
    const unsigned currentResolution = graphics->FindBestResolutionIndex(currentMonitor,
        graphics->GetWidth(), graphics->GetHeight(), graphics->GetRefreshRate());
    resolutionControl_->SetSelection(currentResolution);

    // Synchronize fullscreen and borderless flags
    fullscreenControl_->SetChecked(graphics->GetFullscreen());
    borderlessControl_->SetChecked(graphics->GetBorderless());
    resizableControl_->SetChecked(graphics->GetResizable());
    vsyncControl_->SetChecked(graphics->GetVSync());

    // Synchronize MSAA
    for (unsigned i = 0; i <= 4; ++i)
    {
        if (graphics->GetMultiSample() == static_cast<int>(1 << i))
            multiSampleControl_->SetSelection(i);
    }
}
<commit_msg>Fix build of Sample 54.<commit_after>//
// Copyright (c) 2008-2020 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/GraphicsEvents.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Texture2D.h>
#include <Urho3D/Graphics/Zone.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/CheckBox.h>
#include <Urho3D/UI/DropDownList.h>
#include <Urho3D/UI/LineEdit.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/ToolTip.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/UI/Window.h>

#include "WindowSettingsDemo.h"

#include <Urho3D/DebugNew.h>

URHO3D_DEFINE_APPLICATION_MAIN(WindowSettingsDemo)

WindowSettingsDemo::WindowSettingsDemo(Context* context)
    : Sample(context)
    , uiRoot_(GetSubsystem<UI>()->GetRoot())
{
}

void WindowSettingsDemo::Start()
{
    // Execute base class startup
    Sample::Start();

    // Enable OS cursor
    GetSubsystem<Input>()->SetMouseVisible(true);

    // Load XML file containing default UI style sheet
    auto* cache = GetSubsystem<ResourceCache>();
    auto* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");

    // Set the loaded style as default style
    uiRoot_->SetDefaultStyle(style);

    // Create window with settings.
    InitSettings();
    SynchronizeSettings();
    SubscribeToEvent(E_SCREENMODE,
        [this](StringHash /*eventType*/, const VariantMap& /*eventData*/)
    {
        SynchronizeSettings();
    });

    // Set the mouse mode to use in the sample
    Sample::InitMouseMode(MM_FREE);

    // Create scene
    CreateScene();

    // Setup viewport
    auto* renderer = GetSubsystem<Renderer>();
    SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
    renderer->SetViewport(0, viewport);
}

void WindowSettingsDemo::CreateScene()
{
    auto* cache = GetSubsystem<ResourceCache>();

    scene_ = new Scene(context_);
    scene_->CreateComponent<Octree>();

    auto* zone = scene_->CreateComponent<Zone>();
    zone->SetAmbientColor(Color::WHITE);

    // Create 3D object
    Node* objectNode = scene_->CreateChild("Object");
    objectNode->SetRotation(Quaternion(45.0f, 45.0f, 45.0f));
    auto* objectModel = objectNode->CreateComponent<StaticModel>();
    objectModel->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
    objectModel->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));

    // Create camera
    cameraNode_ = scene_->CreateChild("Camera");
    cameraNode_->CreateComponent<Camera>();
    cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -4.0f));

    // Rotate object
    SubscribeToEvent(scene_, E_SCENEUPDATE,
        [objectNode](StringHash /*eventType*/, VariantMap& eventData)
    {
        const float timeStep = eventData[SceneUpdate::P_TIMESTEP].GetFloat();
        objectNode->Rotate(Quaternion(0.0f, 20.0f * timeStep, 0.0f), TS_WORLD);
    });
}

void WindowSettingsDemo::InitSettings()
{
    auto* graphics = GetSubsystem<Graphics>();

    // Create the Window and add it to the UI's root node
    window_ = uiRoot_->CreateChild<Window>("Window");

    // Set Window size and layout settings
    window_->SetPosition(128, 128);
    window_->SetMinWidth(300);
    window_->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6));
    window_->SetMovable(true);
    window_->SetStyleAuto();

    // Create the Window title Text
    auto* windowTitle = window_->CreateChild<Text>("WindowTitle");
    windowTitle->SetText("Window Settings");
    windowTitle->SetStyleAuto();

    // Create monitor selector
    monitorControl_ = window_->CreateChild<DropDownList>("Monitor");
    monitorControl_->SetMinHeight(24);
    monitorControl_->SetStyleAuto();
    for (int i = 0; i < graphics->GetMonitorCount(); ++i)
    {
        auto text = MakeShared<Text>(context_);
        text->SetText(ToString("Monitor %d", i));
        text->SetMinWidth(CeilToInt(text->GetRowWidth(0) + 10));
        monitorControl_->AddItem(text);
        text->SetStyleAuto();
    }

    // Create resolution selector
    resolutionControl_ = window_->CreateChild<DropDownList>("Resolution");
    resolutionControl_->SetMinHeight(24);
    resolutionControl_->SetStyleAuto();

    auto resolutionPlaceholder = MakeShared<Text>(context_);
    resolutionPlaceholder->SetText("[Cannot fill list of resolutions]");
    resolutionPlaceholder->SetMinWidth(CeilToInt(resolutionPlaceholder->GetRowWidth(0) + 10));
    resolutionControl_->AddItem(resolutionPlaceholder);
    resolutionPlaceholder->SetStyleAuto();

    // Create fullscreen controller
    auto* fullscreenFrame = window_->CreateChild<UIElement>("Fullscreen Frame");
    fullscreenFrame->SetMinHeight(24);
    fullscreenFrame->SetLayout(LM_HORIZONTAL, 6);

    fullscreenControl_ = fullscreenFrame->CreateChild<CheckBox>("Fullscreen Control");
    fullscreenControl_->SetStyleAuto();

    auto* fullscreenText = fullscreenFrame->CreateChild<Text>("Fullscreen Label");
    fullscreenText->SetText("Fullscreen");
    fullscreenText->SetMinWidth(CeilToInt(fullscreenText->GetRowWidth(0) + 10));
    fullscreenText->SetStyleAuto();

    // Create borderless controller
    auto* borderlessFrame = window_->CreateChild<UIElement>("Borderless Frame");
    borderlessFrame->SetMinHeight(24);
    borderlessFrame->SetLayout(LM_HORIZONTAL, 6);

    borderlessControl_ = borderlessFrame->CreateChild<CheckBox>("Borderless Control");
    borderlessControl_->SetStyleAuto();

    auto* borderlessText = borderlessFrame->CreateChild<Text>("Borderless Label");
    borderlessText->SetText("Borderless");
    borderlessText->SetMinWidth(CeilToInt(borderlessText->GetRowWidth(0) + 10));
    borderlessText->SetStyleAuto();

    // Create resizable controller
    auto* resizableFrame = window_->CreateChild<UIElement>("Resizable Frame");
    resizableFrame->SetMinHeight(24);
    resizableFrame->SetLayout(LM_HORIZONTAL, 6);

    resizableControl_ = resizableFrame->CreateChild<CheckBox>("Resizable Control");
    resizableControl_->SetStyleAuto();

    auto* resizableText = resizableFrame->CreateChild<Text>("Resizable Label");
    resizableText->SetText("Resizable");
    resizableText->SetMinWidth(CeilToInt(resizableText->GetRowWidth(0) + 10));
    resizableText->SetStyleAuto();

    // Create resizable controller
    auto* vsyncFrame = window_->CreateChild<UIElement>("V-Sync Frame");
    vsyncFrame->SetMinHeight(24);
    vsyncFrame->SetLayout(LM_HORIZONTAL, 6);

    vsyncControl_ = vsyncFrame->CreateChild<CheckBox>("V-Sync Control");
    vsyncControl_->SetStyleAuto();

    auto* vsyncText = vsyncFrame->CreateChild<Text>("V-Sync Label");
    vsyncText->SetText("V-Sync");
    vsyncText->SetMinWidth(CeilToInt(vsyncText->GetRowWidth(0) + 10));
    vsyncText->SetStyleAuto();

    // Create multi-sample controller from 1 (= 2^0) to 16 (= 2^4)
    multiSampleControl_ = window_->CreateChild<DropDownList>("Multi-Sample Control");
    multiSampleControl_->SetMinHeight(24);
    multiSampleControl_->SetStyleAuto();
    for (int i = 0; i <= 4; ++i)
    {
        auto text = MakeShared<Text>(context_);
        text->SetText(i == 0 ? "No MSAA" : ToString("MSAA x%d", 1 << i));
        text->SetMinWidth(CeilToInt(text->GetRowWidth(0) + 10));
        multiSampleControl_->AddItem(text);
        text->SetStyleAuto();
    }

    // Create "Apply" button
    auto* applyButton = window_->CreateChild<Button>("Apply");
    applyButton->SetLayout(LM_HORIZONTAL, 6, IntRect(6, 6, 6, 6));
    applyButton->SetStyleAuto();

    auto* applyButtonText = applyButton->CreateChild<Text>("Apply Text");
    applyButtonText->SetAlignment(HA_CENTER, VA_CENTER);
    applyButtonText->SetText("Apply");
    applyButtonText->SetStyleAuto();

    applyButton->SetFixedWidth(CeilToInt(applyButtonText->GetRowWidth(0) + 20));
    applyButton->SetFixedHeight(30);

    // Apply settings when "Apply" button is clicked
    SubscribeToEvent(applyButton, E_RELEASED,
        [this, graphics](StringHash /*eventType*/, const VariantMap& /*eventData*/)
    {
        const unsigned monitor = monitorControl_->GetSelection();
        if (monitor == M_MAX_UNSIGNED)
            return;

        const auto& resolutions = graphics->GetResolutions(monitor);
        const unsigned selectedResolution = resolutionControl_->GetSelection();
        if (selectedResolution >= resolutions.Size())
            return;

        const bool fullscreen = fullscreenControl_->IsChecked();
        const bool borderless = borderlessControl_->IsChecked();
        const bool resizable = resizableControl_->IsChecked();
        const bool vsync = vsyncControl_->IsChecked();

        const unsigned multiSampleSelection = multiSampleControl_->GetSelection();
        const int multiSample = multiSampleSelection == M_MAX_UNSIGNED ? 1 : static_cast<int>(1 << multiSampleSelection);

        // TODO: Expose these options too?
        const bool highDPI = graphics->GetHighDPI();
        const bool tripleBuffer = graphics->GetTripleBuffer();

        const int width = resolutions[selectedResolution].x_;
        const int height = resolutions[selectedResolution].y_;
        const int refreshRate = resolutions[selectedResolution].z_;
        graphics->SetMode(width, height, fullscreen, borderless, resizable, highDPI, vsync, tripleBuffer, multiSample, monitor, refreshRate);
    });
}

void WindowSettingsDemo::SynchronizeSettings()
{
    auto* graphics = GetSubsystem<Graphics>();

    // Synchronize monitor
    const unsigned currentMonitor = graphics->GetMonitor();
    monitorControl_->SetSelection(currentMonitor);

    // Synchronize resolution list
    resolutionControl_->RemoveAllItems();
    const auto& resolutions = graphics->GetResolutions(currentMonitor);
    for (const IntVector3& resolutions : resolutions)
    {
        auto resolutionEntry = MakeShared<Text>(context_);
        resolutionEntry->SetText(ToString("%dx%d, %d Hz", resolutions.x_, resolutions.y_, resolutions.z_));
        resolutionEntry->SetMinWidth(CeilToInt(resolutionEntry->GetRowWidth(0) + 10));
        resolutionControl_->AddItem(resolutionEntry);
        resolutionEntry->SetStyleAuto();
    }

    // Synchronize selected resolution
    const unsigned currentResolution = graphics->FindBestResolutionIndex(currentMonitor,
        graphics->GetWidth(), graphics->GetHeight(), graphics->GetRefreshRate());
    resolutionControl_->SetSelection(currentResolution);

    // Synchronize fullscreen and borderless flags
    fullscreenControl_->SetChecked(graphics->GetFullscreen());
    borderlessControl_->SetChecked(graphics->GetBorderless());
    resizableControl_->SetChecked(graphics->GetResizable());
    vsyncControl_->SetChecked(graphics->GetVSync());

    // Synchronize MSAA
    for (unsigned i = 0; i <= 4; ++i)
    {
        if (graphics->GetMultiSample() == static_cast<int>(1 << i))
            multiSampleControl_->SetSelection(i);
    }
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt 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 notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {fixed.tif}, {moving.tif}
//    OUTPUTS: {deformationFieldOutput2.png} {resampledOutput2.png}
//    5 1.0 2
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example demonstrates the use of the \doxygen{otb}{NCCRegistrationFilter}. This filter performs deformation estimation
// by optimising a PDE based on correlation. This use the finite difference solver hierarchy.
//
// The first step toward the use of these filters is to include the proper header files.
//
// Software Guide : EndLatex

#include "otbImage.h"
#include "otbImageFileWriter.h"
#include "otbImageFileReader.h"
#include "otbCommandLineArgumentParser.h"

// Software Guide : BeginCodeSnippet
#include "otbNCCRegistrationFilter.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkWarpImageFilter.h"
// Software Guide : EndCodeSnippet

#include <iostream>

int main(int argc, char** argv )
{

  if(argc!= 8)
  {
    std::cerr <<"Usage: "<<argv[0];
    std::cerr<<"fixedFileName movingFileName fieldOutName imageOutName ";
    std::cerr<<"explorationSize bluringSigma nbIterations ";

    return EXIT_FAILURE;
  }

  const unsigned int ImageDimension = 2;

  typedef double                                PixelType;
  typedef itk::Vector<double,ImageDimension>    DeformationPixelType;

  typedef double                   CoordinateRepresentationType;

    // Software Guide : BeginLatex
  //
   // Several type of \doxygen{otb}{Image} are required to represent the reference image (fixed)
  // the image we want to register (moving) and the deformation field.
  //
   // Software Guide : EndLatex

  //Allocate Images
  // Software Guide : BeginCodeSnippet
  typedef otb::Image<PixelType,ImageDimension>         MovingImageType;
  typedef otb::Image<PixelType,ImageDimension>         FixedImageType;
  typedef otb::Image<DeformationPixelType,
                               ImageDimension>         DeformationFieldType;
  // Software Guide : EndCodeSnippet

  typedef otb::ImageFileReader< FixedImageType > FixedReaderType;
  FixedReaderType::Pointer fReader = FixedReaderType::New();
  fReader->SetFileName(argv[1]);

  typedef otb::ImageFileReader< MovingImageType > MovingReaderType;
  MovingReaderType::Pointer mReader = MovingReaderType::New();
  mReader->SetFileName(argv[2]);

  // Software Guide : BeginLatex
  //
  // To make the correlation possible and to avoid some local minima the first required step is
  // to blur the input images. This is done using the \doxygen{itk}{RecursiveGaussianImageFilter}:
  //
  // Software Guide : EndLatex

  //Blur input images
  // Software Guide : BeginCodeSnippet
  typedef itk::RecursiveGaussianImageFilter< FixedImageType,
    FixedImageType > FixedBlurType;

  FixedBlurType::Pointer fBlur = FixedBlurType::New();
  fBlur->SetInput( fReader->GetOutput() );
  fBlur->SetSigma( atof(argv[6]) );

  typedef itk::RecursiveGaussianImageFilter< MovingImageType,
    MovingImageType > MovingBlurType;

  MovingBlurType::Pointer mBlur = MovingBlurType::New();
  mBlur->SetInput( mReader->GetOutput() );
  mBlur->SetSigma(atof(argv[6]) );
// Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Now, we need to instanciate the NCCRegistrationFilter which is going to perform the registration:
  //
  // Software Guide : EndLatex

  //Create the filter
  // Software Guide : BeginCodeSnippet
  typedef otb::NCCRegistrationFilter< FixedImageType,
                                       MovingImageType,
                                       DeformationFieldType >
                                           RegistrationFilterType;

  RegistrationFilterType::Pointer registrator = RegistrationFilterType::New();

  registrator->SetMovingImage( mBlur->GetOutput() );
  registrator->SetFixedImage( fBlur->GetOutput() );
// Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Few parameters need to be specified to the NCCRegistrationFilter:
  // \begin{itemize}
  // \item The area where the search is performed. This area is defined by its radius:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef RegistrationFilterType::RadiusType RadiusType;

  RadiusType radius;

  radius[0] = atoi(argv[5]);
  radius[1] = atoi(argv[5]);

  registrator->SetNCCRadius( radius );
// Software Guide : EndCodeSnippet

  std::cout << "NCC radius " << registrator->GetNCCRadius() << std::endl;

  // Software Guide : BeginLatex
  //
  // \item The number of iteration for the PDE resolution:
  //
  // Software Guide : EndLatex

   // Software Guide : BeginCodeSnippet
  registrator->SetNumberOfIterations( atoi(argv[7]) );
// Software Guide : EndCodeSnippet
  // registrator->GetDeformationField();

  // Software Guide : BeginLatex
  //
  // \end{itemize}
  // Then we can trigger the \code{Update()} method on the NCCRegistrationFilter:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  registrator->Update();
  // Software Guide : EndCodeSnippet

  typedef otb::ImageFileWriter< DeformationFieldType > DFWriterType;

  DFWriterType::Pointer dfWriter = DFWriterType::New();
  dfWriter->SetFileName(argv[3]);
  dfWriter->SetInput( registrator->GetOutput() );
  dfWriter->Update();

  typedef itk::WarpImageFilter<MovingImageType, MovingImageType, DeformationFieldType> WarperType;
  WarperType::Pointer warper = WarperType::New();

  MovingImageType::PixelType padValue = 4.0;

  warper->SetInput( mReader->GetOutput() );
  warper->SetDeformationField( registrator->GetOutput() );
  warper->SetEdgePaddingValue( padValue );

  typedef otb::ImageFileWriter< MovingImageType > WriterType;

  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(argv[4]);
  writer->SetInput( warper->GetOutput() );
  writer->Update();

  // Software Guide : BeginLatex
  //
  // Figure~\ref{fig:NCCRegistrationFilterOUTPUT} shows the result of applying.
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.40\textwidth]{}
  // \includegraphics[width=0.40\textwidth]{}
  // \includegraphics[width=0.40\textwidth]{}
  // \includegraphics[width=0.40\textwidth]{}
  // \itkcaption[Deformation field and resampling from NCC registration]{From left
  // to right and top to bottom: fixed input image, moving image with a low stereo angle,
  // estimated deformation field in the horizontal direction, resampled moving image.}
  // \label{fig:NCCRegistrationFilterOUTPUT}
  // \end{figure}
  //
  // Software Guide : EndLatex

  return EXIT_SUCCESS;

}

<commit_msg>DOC: Updated input images for NCCRegistrationFilterExample<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt 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 notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {StereoFixed.png}, {StereoMoving.png}
//    OUTPUTS: {deformationFieldOutput2.png} {resampledOutput2.png}
//    5 1.0 2
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example demonstrates the use of the \doxygen{otb}{NCCRegistrationFilter}. This filter performs deformation estimation
// by optimising a PDE based on correlation. This use the finite difference solver hierarchy.
//
// The first step toward the use of these filters is to include the proper header files.
//
// Software Guide : EndLatex

#include "otbImage.h"
#include "otbImageFileWriter.h"
#include "otbImageFileReader.h"
#include "otbCommandLineArgumentParser.h"

// Software Guide : BeginCodeSnippet
#include "otbNCCRegistrationFilter.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkWarpImageFilter.h"
// Software Guide : EndCodeSnippet

#include <iostream>

int main(int argc, char** argv )
{

  if(argc!= 8)
  {
    std::cerr <<"Usage: "<<argv[0];
    std::cerr<<"fixedFileName movingFileName fieldOutName imageOutName ";
    std::cerr<<"explorationSize bluringSigma nbIterations ";

    return EXIT_FAILURE;
  }

  const unsigned int ImageDimension = 2;

  typedef double                                PixelType;
  typedef itk::Vector<double,ImageDimension>    DeformationPixelType;

  typedef double                   CoordinateRepresentationType;

    // Software Guide : BeginLatex
  //
   // Several type of \doxygen{otb}{Image} are required to represent the reference image (fixed)
  // the image we want to register (moving) and the deformation field.
  //
   // Software Guide : EndLatex

  //Allocate Images
  // Software Guide : BeginCodeSnippet
  typedef otb::Image<PixelType,ImageDimension>         MovingImageType;
  typedef otb::Image<PixelType,ImageDimension>         FixedImageType;
  typedef otb::Image<DeformationPixelType,
                               ImageDimension>         DeformationFieldType;
  // Software Guide : EndCodeSnippet

  typedef otb::ImageFileReader< FixedImageType > FixedReaderType;
  FixedReaderType::Pointer fReader = FixedReaderType::New();
  fReader->SetFileName(argv[1]);

  typedef otb::ImageFileReader< MovingImageType > MovingReaderType;
  MovingReaderType::Pointer mReader = MovingReaderType::New();
  mReader->SetFileName(argv[2]);

  // Software Guide : BeginLatex
  //
  // To make the correlation possible and to avoid some local minima the first required step is
  // to blur the input images. This is done using the \doxygen{itk}{RecursiveGaussianImageFilter}:
  //
  // Software Guide : EndLatex

  //Blur input images
  // Software Guide : BeginCodeSnippet
  typedef itk::RecursiveGaussianImageFilter< FixedImageType,
    FixedImageType > FixedBlurType;

  FixedBlurType::Pointer fBlur = FixedBlurType::New();
  fBlur->SetInput( fReader->GetOutput() );
  fBlur->SetSigma( atof(argv[6]) );

  typedef itk::RecursiveGaussianImageFilter< MovingImageType,
    MovingImageType > MovingBlurType;

  MovingBlurType::Pointer mBlur = MovingBlurType::New();
  mBlur->SetInput( mReader->GetOutput() );
  mBlur->SetSigma(atof(argv[6]) );
// Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Now, we need to instanciate the NCCRegistrationFilter which is going to perform the registration:
  //
  // Software Guide : EndLatex

  //Create the filter
  // Software Guide : BeginCodeSnippet
  typedef otb::NCCRegistrationFilter< FixedImageType,
                                       MovingImageType,
                                       DeformationFieldType >
                                           RegistrationFilterType;

  RegistrationFilterType::Pointer registrator = RegistrationFilterType::New();

  registrator->SetMovingImage( mBlur->GetOutput() );
  registrator->SetFixedImage( fBlur->GetOutput() );
// Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Few parameters need to be specified to the NCCRegistrationFilter:
  // \begin{itemize}
  // \item The area where the search is performed. This area is defined by its radius:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef RegistrationFilterType::RadiusType RadiusType;

  RadiusType radius;

  radius[0] = atoi(argv[5]);
  radius[1] = atoi(argv[5]);

  registrator->SetNCCRadius( radius );
// Software Guide : EndCodeSnippet

  std::cout << "NCC radius " << registrator->GetNCCRadius() << std::endl;

  // Software Guide : BeginLatex
  //
  // \item The number of iteration for the PDE resolution:
  //
  // Software Guide : EndLatex

   // Software Guide : BeginCodeSnippet
  registrator->SetNumberOfIterations( atoi(argv[7]) );
// Software Guide : EndCodeSnippet
  // registrator->GetDeformationField();

  // Software Guide : BeginLatex
  //
  // \end{itemize}
  // Then we can trigger the \code{Update()} method on the NCCRegistrationFilter:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  registrator->Update();
  // Software Guide : EndCodeSnippet

  typedef otb::ImageFileWriter< DeformationFieldType > DFWriterType;

  DFWriterType::Pointer dfWriter = DFWriterType::New();
  dfWriter->SetFileName(argv[3]);
  dfWriter->SetInput( registrator->GetOutput() );
  dfWriter->Update();

  typedef itk::WarpImageFilter<MovingImageType, MovingImageType, DeformationFieldType> WarperType;
  WarperType::Pointer warper = WarperType::New();

  MovingImageType::PixelType padValue = 4.0;

  warper->SetInput( mReader->GetOutput() );
  warper->SetDeformationField( registrator->GetOutput() );
  warper->SetEdgePaddingValue( padValue );

  typedef otb::ImageFileWriter< MovingImageType > WriterType;

  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(argv[4]);
  writer->SetInput( warper->GetOutput() );
  writer->Update();

  // Software Guide : BeginLatex
  //
  // Figure~\ref{fig:NCCRegistrationFilterOUTPUT} shows the result of applying.
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.40\textwidth]{}
  // \includegraphics[width=0.40\textwidth]{}
  // \includegraphics[width=0.40\textwidth]{}
  // \includegraphics[width=0.40\textwidth]{}
  // \itkcaption[Deformation field and resampling from NCC registration]{From left
  // to right and top to bottom: fixed input image, moving image with a low stereo angle,
  // estimated deformation field in the horizontal direction, resampled moving image.}
  // \label{fig:NCCRegistrationFilterOUTPUT}
  // \end{figure}
  //
  // Software Guide : EndLatex

  return EXIT_SUCCESS;

}

<|endoftext|>