<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - The Lightweight Desktop Environment
 * https://lxqt.org
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Petr Vanek <petr@scribus.info>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "lxqtaboutdialog.h"
#include "ui_lxqtaboutdialog.h"
#include "lxqtaboutdialog_p.h"
#include "technicalinfo.h"
#include "translatorsinfo/translatorsinfo.h"

#include <QDebug>
#include <QDate>
#include <QClipboard>

AboutDialogPrivate::AboutDialogPrivate()
{
    setupUi(this);

    QString css=QStringLiteral("")
            ;

    iconLabel->setFixedSize(48, 48);
    iconLabel->setScaledContents(true);
    iconLabel->setPixmap(QPixmap(QStringLiteral(LXQT_SHARE_DIR) + QStringLiteral("/graphics/lxqt_logo.png")));

    nameLabel->setText(css + titleText());

    aboutBrowser->setHtml(css + aboutText());
    aboutBrowser->viewport()->setAutoFillBackground(false);

    autorsBrowser->setHtml(css + authorsText());
    autorsBrowser->viewport()->setAutoFillBackground(false);

    thanksBrowser->setHtml(css + thanksText());
    thanksBrowser->viewport()->setAutoFillBackground(false);

    translationsBrowser->setHtml(css + translationsText());
    translationsBrowser->viewport()->setAutoFillBackground(false);

    TechnicalInfo info;
    techBrowser->setHtml(info.html());
    techBrowser->viewport()->setAutoFillBackground(false);

    connect(techCopyToClipboardButton, SIGNAL(clicked()), this, SLOT(copyToCliboardTechInfo()));
    this->setAttribute(Qt::WA_DeleteOnClose);
    show();

}

QString AboutDialogPrivate::titleText() const
{
    return QStringLiteral("
%1

%2
").arg(QStringLiteral("LXQt"),
                tr("Version: %1").arg(QStringLiteral(LXQT_VERSION)));

}

QString AboutDialogPrivate::aboutText() const
{
    return QStringLiteral(
        "
%1
"
        "
%2
"
        "
%3
"
        "
%4
"
        "
%5
")
        .arg(
            tr("Advanced, easy-to-use, and fast desktop environment based on Qt technologies.",
               "About dialog, 'About' tab text"),
            tr("LXQt would not have been possible without the Razor-qt project and its many contributors.",
               "About dialog, 'About' tab text").arg(QStringLiteral("href=\"https://blog.lxqt.org/2014/11/in-memory-of-razor-qt/\"")),
            tr("Copyright: © %1-%2 %3", "About dialog, 'About' tab text")
                .arg(QStringLiteral("2010"), QDate::currentDate().toString(QStringLiteral("yyyy")), QStringLiteral("LXQt team")),
            tr("Homepage: %1", "About dialog, 'About' tab text")
                .arg(QStringLiteral("https://lxqt.github.io")),
            tr("License: %1", "About dialog, 'About' tab text")
                .arg(QStringLiteral("GNU Lesser General Public License version 2.1 or later"
                     " and partly under the "
                     "GNU General Public License version 2"))
            );
}

QString AboutDialogPrivate::authorsText() const
{
    return QStringLiteral("
%1

%2
").arg(
                tr("LXQt is developed by the LXQt Team and contributors.", "About dialog, 'Authors' tab text")
                    .arg(QStringLiteral(" href=\"https://github.com/lxqt/lxqt\"")),
                tr("If you are interested in working with our development team, join us.", "About dialog, 'Authors' tab text")
                    .arg(QStringLiteral("href=\"https://lxqt.github.io\""))
                );
}

QString AboutDialogPrivate::thanksText() const
{
    return QStringLiteral(
                "%1"
                "
"
                "
Alexey Nosov (for the A-MeGo theme)
"
                "
Alexander Zakher (the Razor-qt name)
"
                "
Andy Fitzsimon (logo/icon)
"
                "
Eugene Pivnev (QtDesktop)
"
                "
Manuel Meier (for ideas)
"
                "
KDE <https://kde.org/>
"
                ).arg(tr("Special thanks to:", "About dialog, 'Thanks' tab text"));
}

QString AboutDialogPrivate::translationsText() const
{
    TranslatorsInfo translatorsInfo;
    return QStringLiteral("%1

%2
").arg(
                tr("LXQt is translated into many languages thanks to the work of the translation teams all over the world.", "About dialog, 'Translations' tab text"),
                translatorsInfo.asHtml()
                );
}

AboutDialog::AboutDialog()
{
    d_ptr = new AboutDialogPrivate();
}

void AboutDialogPrivate::copyToCliboardTechInfo()
{
    TechnicalInfo info;
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(info.text());
}
<commit_msg>Fixed Razor-qt link<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - The Lightweight Desktop Environment
 * https://lxqt.org
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Petr Vanek <petr@scribus.info>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "lxqtaboutdialog.h"
#include "ui_lxqtaboutdialog.h"
#include "lxqtaboutdialog_p.h"
#include "technicalinfo.h"
#include "translatorsinfo/translatorsinfo.h"

#include <QDebug>
#include <QDate>
#include <QClipboard>

AboutDialogPrivate::AboutDialogPrivate()
{
    setupUi(this);

    QString css=QStringLiteral("")
            ;

    iconLabel->setFixedSize(48, 48);
    iconLabel->setScaledContents(true);
    iconLabel->setPixmap(QPixmap(QStringLiteral(LXQT_SHARE_DIR) + QStringLiteral("/graphics/lxqt_logo.png")));

    nameLabel->setText(css + titleText());

    aboutBrowser->setHtml(css + aboutText());
    aboutBrowser->viewport()->setAutoFillBackground(false);

    autorsBrowser->setHtml(css + authorsText());
    autorsBrowser->viewport()->setAutoFillBackground(false);

    thanksBrowser->setHtml(css + thanksText());
    thanksBrowser->viewport()->setAutoFillBackground(false);

    translationsBrowser->setHtml(css + translationsText());
    translationsBrowser->viewport()->setAutoFillBackground(false);

    TechnicalInfo info;
    techBrowser->setHtml(info.html());
    techBrowser->viewport()->setAutoFillBackground(false);

    connect(techCopyToClipboardButton, SIGNAL(clicked()), this, SLOT(copyToCliboardTechInfo()));
    this->setAttribute(Qt::WA_DeleteOnClose);
    show();

}

QString AboutDialogPrivate::titleText() const
{
    return QStringLiteral("
%1

%2
").arg(QStringLiteral("LXQt"),
                tr("Version: %1").arg(QStringLiteral(LXQT_VERSION)));

}

QString AboutDialogPrivate::aboutText() const
{
    return QStringLiteral(
        "
%1
"
        "
%2
"
        "
%3
"
        "
%4
"
        "
%5
")
        .arg(
            tr("Advanced, easy-to-use, and fast desktop environment based on Qt technologies.",
               "About dialog, 'About' tab text"),
            tr("LXQt would not have been possible without the Razor-qt project and its many contributors.",
               "About dialog, 'About' tab text").arg(QStringLiteral("href=\"https://blog.lxde.org/2014/11/21/in-memory-of-razor-qt/\"")),
            tr("Copyright: © %1-%2 %3", "About dialog, 'About' tab text")
                .arg(QStringLiteral("2010"), QDate::currentDate().toString(QStringLiteral("yyyy")), QStringLiteral("LXQt team")),
            tr("Homepage: %1", "About dialog, 'About' tab text")
                .arg(QStringLiteral("https://lxqt.github.io")),
            tr("License: %1", "About dialog, 'About' tab text")
                .arg(QStringLiteral("GNU Lesser General Public License version 2.1 or later"
                     " and partly under the "
                     "GNU General Public License version 2"))
            );
}

QString AboutDialogPrivate::authorsText() const
{
    return QStringLiteral("
%1

%2
").arg(
                tr("LXQt is developed by the LXQt Team and contributors.", "About dialog, 'Authors' tab text")
                    .arg(QStringLiteral(" href=\"https://github.com/lxqt/lxqt\"")),
                tr("If you are interested in working with our development team, join us.", "About dialog, 'Authors' tab text")
                    .arg(QStringLiteral("href=\"https://lxqt.github.io\""))
                );
}

QString AboutDialogPrivate::thanksText() const
{
    return QStringLiteral(
                "%1"
                "
"
                "
Alexey Nosov (for the A-MeGo theme)
"
                "
Alexander Zakher (the Razor-qt name)
"
                "
Andy Fitzsimon (logo/icon)
"
                "
Eugene Pivnev (QtDesktop)
"
                "
Manuel Meier (for ideas)
"
                "
KDE <https://kde.org/>
"
                ).arg(tr("Special thanks to:", "About dialog, 'Thanks' tab text"));
}

QString AboutDialogPrivate::translationsText() const
{
    TranslatorsInfo translatorsInfo;
    return QStringLiteral("%1

%2
").arg(
                tr("LXQt is translated into many languages thanks to the work of the translation teams all over the world.", "About dialog, 'Translations' tab text"),
                translatorsInfo.asHtml()
                );
}

AboutDialog::AboutDialog()
{
    d_ptr = new AboutDialogPrivate();
}

void AboutDialogPrivate::copyToCliboardTechInfo()
{
    TechnicalInfo info;
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(info.text());
}
<|endoftext|>


<commit_before>#include "GLFramebuffer.h"

#include "GL.h"
#include "GLRenderbuffer.h"
#include "GLRenderTexture2D.h"
#include "GLRenderTexture2DRectangle.h"

#include <iostream>
#include "GLUtility.h"

using namespace std;

// ----------------------------------------------------------------------------
// Need to use this factory to create FBOs
GLFramebuffer* GLFramebuffer::New(int width, int height)
{
	// Check for framebuffer support
	if (!GLEW_EXT_framebuffer_object)
	{
		// Oops, not supported
		cerr << "GLFramebuffer: Framebuffer objects not supported!" << endl;
		return 0;
	}

	// Create and return new FBO
	return new GLFramebuffer(width, height);
}

// ----------------------------------------------------------------------------
GLFramebuffer::GLFramebuffer(int width, int height)
: id(0), width(width), height(height), bound(false)
{
	// Create the framebuffer
	//cout << "GLFramebuffer: Constructor" << endl;
	glGenFramebuffersEXT(1, &id);
#ifndef NDEBUG
	GLUtility::CheckOpenGLError("GLFramebuffer: glGenFramebuffersEXT()");
#endif
}

// ----------------------------------------------------------------------------
GLFramebuffer::~GLFramebuffer()
{
	//cout << "GLFramebuffer: Destructor" << endl;

	// Delete all attachments
	for (map<int, GLRendertarget*>::iterator i = attachments.begin(); i != attachments.end(); )
	{
		int attachment = i->first;
		i++;
		GLRendertarget *rt = DetachRendertarget(attachment);
		// Delete the rendertarget if it's no longer attached anywhere
		if (rt->GetTimesAttached() == 0) delete rt;
	}
	// Delete the framebuffer
	glDeleteFramebuffersEXT(1, &id);
#ifndef NDEBUG
	GLUtility::CheckOpenGLError("GLFramebuffer: glDeleteFramebuffersEXT()");
#endif
}

// ----------------------------------------------------------------------------
GLRendertarget *GLFramebuffer::AttachRendertarget(int attachment, GLRendertarget *rt)
{
	if (!rt)
	{
		return DetachRendertarget(attachment);
	}
	else
	{
		return AttachRendertarget(attachment, *rt);
	}
}

// ----------------------------------------------------------------------------
GLRendertarget *GLFramebuffer::AttachRendertarget(int attachment, GLRendertarget &rt)
{
	if (!bound) Bind();

	// Remove the old render target (if any)
	GLRendertarget *oldRt = DetachRendertarget(attachment);

	// Attach the new target
	rt.AttachToBoundFBO(attachment);
	attachments[attachment] = &rt;

	// Return the old attachment (or null)
	return oldRt;
}

// ----------------------------------------------------------------------------
GLRendertarget* GLFramebuffer::DetachRendertarget(int attachment)
{
	if (!bound) Bind();

	// Release the old render target (if any) to the caller and remove it from the map
	GLRendertarget *rt = 0;
	map<int, GLRendertarget*>::iterator it = attachments.find(attachment);
	if (it != attachments.end())
	{
		rt = it->second;
		rt->DetachFromBoundFBO(attachment);
	}
	attachments.erase(attachment);

	return rt;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateDepthBuffer(int format)
{
	// Abuse the color buffer utility functions
	return CreateColorBuffer(GL_DEPTH_ATTACHMENT_EXT, format);
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateDepthTexture(int format)
{
	// Abuse the color buffer utility functions
	return CreateColorTexture(GL_DEPTH_ATTACHMENT_EXT,
		format, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE);
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateDepthTextureRectangle(int format)
{
	// Abuse the color buffer utility functions
	return CreateColorTextureRectangle(GL_DEPTH_ATTACHMENT_EXT,
		format, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE);
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreatePackedDepthStencilBuffer()
{
	if (!GLEW_EXT_packed_depth_stencil) return false;

	GLRendertarget *dsb = GLRenderbuffer::New(width, height, GL_DEPTH24_STENCIL8_EXT);
	// Attach as depth buffer
	GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}
	// Attach as stencil
	old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreatePackedDepthStencilTexture()
{
	if (!GLEW_EXT_packed_depth_stencil) return false;
	if (!GLEW_ARB_depth_texture && !GLEW_SGIX_depth_texture) return false;

	GLRendertarget *dsb = GLRenderTexture2D::New(width, height,
		GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT);
	// Attach as depth buffer
	GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}
	// Attach as stencil
	old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreatePackedDepthStencilTextureRectangle()
{
	if (!GLEW_ARB_texture_rectangle) return false;
	if (!GLEW_EXT_packed_depth_stencil) return false;
	if (!GLEW_ARB_depth_texture && !GLEW_SGIX_depth_texture) return false;

	GLRendertarget *dsb = GLRenderTexture2DRectangle::New(width, height,
		GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT);
	// Attach as depth buffer
	GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}
	// Attach as stencil
	old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateColorBuffer(int attachment, int format)
{
	GLRendertarget *buffer = GLRenderbuffer::New(
		width, height, format);
	// Attach to target
	GLRendertarget *old = AttachRendertarget(attachment, *buffer);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateColorTexture(int attachment,
									   int internalformat,
									   int format, int type)
{
	GLRendertarget *buffer = GLRenderTexture2D::New(
		width, height, internalformat, format, type);
	// Attach to target
	GLRendertarget *old = AttachRendertarget(attachment, *buffer);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateColorTextureRectangle(int attachment,
												int internalformat,
												int format, int type)
{
	if (!GLEW_ARB_texture_rectangle) return false;

	GLRendertarget *buffer = GLRenderTexture2DRectangle::New(
		width, height, internalformat, format, type);
	// Attach to target
	GLRendertarget *old = AttachRendertarget(attachment, *buffer);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
void GLFramebuffer::Bind()
{
	if (bound)
	{
		cerr << "GLFramebuffer: Bind() called, but framebuffer was already bound" << endl;
		return;
	}

	// Store old viewport
	glPushAttrib(GL_VIEWPORT_BIT);
	// Bind FBO
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id);
	// Set viewport
	glViewport(0, 0, width, height);
	bound = true;
#ifndef NDEBUG
	GLUtility::CheckOpenGLError("GLFramebuffer: Bind()");
#endif
}

// ----------------------------------------------------------------------------
void GLFramebuffer::Unbind()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

	if (bound)
	{
		// Restore viewport
		glPopAttrib();
	}
	else
	{
		cerr << "GLFramebuffer: Unbind() called, but framebuffer was not bound" << endl;
	}

	bound = false;

#ifndef NDEBUG
	GLUtility::CheckOpenGLError("GLFramebuffer: Unbind()");
#endif
}

// ----------------------------------------------------------------------------
int GLFramebuffer::GetStatus()
{
	if (!bound) Bind();
	return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::IsOk()
{
	int status = GetStatus();
	switch (status)
	{
		case GL_FRAMEBUFFER_COMPLETE_EXT:
			return true;
			break;
		case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
			return false;
			break;
		default:
			//assert(false); // Error in framebuffer code!
			return false;
			break;
	}
}

// ----------------------------------------------------------------------------
GLTexture* GLFramebuffer::GetTexture2D(int attachment)
{
	// Try to cast, return null if that attachment isn't a rendertarget
	GLRenderTexture2D *rt = dynamic_cast<GLRenderTexture2D*>(attachments[attachment]);
	if (!rt) return 0;
	// Return texture
	return rt->GetTexture();
}

// ----------------------------------------------------------------------------
const GLTexture* GLFramebuffer::GetTexture2D(int attachment) const
{
	// Try to cast, return null if that attachment isn't a rendertarget
	map<int, GLRendertarget*>::const_iterator atit = attachments.find(attachment);
	if (atit == attachments.end()) return 0;
	const GLRenderTexture2D *rt = dynamic_cast<const GLRenderTexture2D*>(atit->second);
	if (!rt) return 0;
	// Return texture
	return rt->GetTexture();
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::Resize(int width, int height)
{
	// Resize all attachments
	for (map<int, GLRendertarget*>::iterator i = attachments.begin(); i != attachments.end(); )
	{
		int attachment = i->first;
		i++;
		// We need to detach, because the internal rendertarget might change
		GLRendertarget *rt = DetachRendertarget(attachment);
		if (!rt->Resize(width, height))
		{
			cerr << "GLFrameBuffer: Resize failed for attachment " << attachment << endl;
			delete rt;
			return false;
		}
		// Re-attach the rendertarget
		AttachRendertarget(attachment, *rt);
	}

	// Update framebuffer size
	this->width = width;
	this->height = height;

	// Unbind the framebuffer if bound
	if (bound) Unbind();

	return true;
}
<commit_msg>Fixed bug where ghost attachments could be created by requesting an invalid attachment's texture.<commit_after>#include "GLFramebuffer.h"

#include "GL.h"
#include "GLRenderbuffer.h"
#include "GLRenderTexture2D.h"
#include "GLRenderTexture2DRectangle.h"

#include <iostream>
#include "GLUtility.h"

using namespace std;

// ----------------------------------------------------------------------------
// Need to use this factory to create FBOs
GLFramebuffer* GLFramebuffer::New(int width, int height)
{
	// Check for framebuffer support
	if (!GLEW_EXT_framebuffer_object)
	{
		// Oops, not supported
		cerr << "GLFramebuffer: Framebuffer objects not supported!" << endl;
		return 0;
	}

	// Create and return new FBO
	return new GLFramebuffer(width, height);
}

// ----------------------------------------------------------------------------
GLFramebuffer::GLFramebuffer(int width, int height)
: id(0), width(width), height(height), bound(false)
{
	// Create the framebuffer
	//cout << "GLFramebuffer: Constructor" << endl;
	glGenFramebuffersEXT(1, &id);
#ifndef NDEBUG
	GLUtility::CheckOpenGLError("GLFramebuffer: glGenFramebuffersEXT()");
#endif
}

// ----------------------------------------------------------------------------
GLFramebuffer::~GLFramebuffer()
{
	//cout << "GLFramebuffer: Destructor" << endl;

	// Delete all attachments
	for (map<int, GLRendertarget*>::iterator i = attachments.begin(); i != attachments.end(); )
	{
		int attachment = i->first;
		i++;
		GLRendertarget *rt = DetachRendertarget(attachment);
		// Delete the rendertarget if it's no longer attached anywhere
		if (rt->GetTimesAttached() == 0) delete rt;
	}
	// Delete the framebuffer
	glDeleteFramebuffersEXT(1, &id);
#ifndef NDEBUG
	GLUtility::CheckOpenGLError("GLFramebuffer: glDeleteFramebuffersEXT()");
#endif
}

// ----------------------------------------------------------------------------
GLRendertarget *GLFramebuffer::AttachRendertarget(int attachment, GLRendertarget *rt)
{
	if (!rt)
	{
		return DetachRendertarget(attachment);
	}
	else
	{
		return AttachRendertarget(attachment, *rt);
	}
}

// ----------------------------------------------------------------------------
GLRendertarget *GLFramebuffer::AttachRendertarget(int attachment, GLRendertarget &rt)
{
	if (!bound) Bind();

	// Remove the old render target (if any)
	GLRendertarget *oldRt = DetachRendertarget(attachment);

	// Attach the new target
	rt.AttachToBoundFBO(attachment);
	attachments[attachment] = &rt;

	// Return the old attachment (or null)
	return oldRt;
}

// ----------------------------------------------------------------------------
GLRendertarget* GLFramebuffer::DetachRendertarget(int attachment)
{
	if (!bound) Bind();

	// Release the old render target (if any) to the caller and remove it from the map
	GLRendertarget *rt = 0;
	map<int, GLRendertarget*>::iterator it = attachments.find(attachment);
	if (it != attachments.end())
	{
		rt = it->second;
		rt->DetachFromBoundFBO(attachment);
	}
	attachments.erase(attachment);

	return rt;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateDepthBuffer(int format)
{
	// Abuse the color buffer utility functions
	return CreateColorBuffer(GL_DEPTH_ATTACHMENT_EXT, format);
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateDepthTexture(int format)
{
	// Abuse the color buffer utility functions
	return CreateColorTexture(GL_DEPTH_ATTACHMENT_EXT,
		format, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE);
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateDepthTextureRectangle(int format)
{
	// Abuse the color buffer utility functions
	return CreateColorTextureRectangle(GL_DEPTH_ATTACHMENT_EXT,
		format, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE);
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreatePackedDepthStencilBuffer()
{
	if (!GLEW_EXT_packed_depth_stencil) return false;

	GLRendertarget *dsb = GLRenderbuffer::New(width, height, GL_DEPTH24_STENCIL8_EXT);
	// Attach as depth buffer
	GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}
	// Attach as stencil
	old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreatePackedDepthStencilTexture()
{
	if (!GLEW_EXT_packed_depth_stencil) return false;
	if (!GLEW_ARB_depth_texture && !GLEW_SGIX_depth_texture) return false;

	GLRendertarget *dsb = GLRenderTexture2D::New(width, height,
		GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT);
	// Attach as depth buffer
	GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}
	// Attach as stencil
	old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreatePackedDepthStencilTextureRectangle()
{
	if (!GLEW_ARB_texture_rectangle) return false;
	if (!GLEW_EXT_packed_depth_stencil) return false;
	if (!GLEW_ARB_depth_texture && !GLEW_SGIX_depth_texture) return false;

	GLRendertarget *dsb = GLRenderTexture2DRectangle::New(width, height,
		GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT);
	// Attach as depth buffer
	GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}
	// Attach as stencil
	old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateColorBuffer(int attachment, int format)
{
	GLRendertarget *buffer = GLRenderbuffer::New(
		width, height, format);
	// Attach to target
	GLRendertarget *old = AttachRendertarget(attachment, *buffer);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateColorTexture(int attachment,
									   int internalformat,
									   int format, int type)
{
	GLRendertarget *buffer = GLRenderTexture2D::New(
		width, height, internalformat, format, type);
	// Attach to target
	GLRendertarget *old = AttachRendertarget(attachment, *buffer);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::CreateColorTextureRectangle(int attachment,
												int internalformat,
												int format, int type)
{
	if (!GLEW_ARB_texture_rectangle) return false;

	GLRendertarget *buffer = GLRenderTexture2DRectangle::New(
		width, height, internalformat, format, type);
	// Attach to target
	GLRendertarget *old = AttachRendertarget(attachment, *buffer);
	if (old)
	{
		if (old->GetTimesAttached() == 0) delete old;
	}

	return true;
}

// ----------------------------------------------------------------------------
void GLFramebuffer::Bind()
{
	if (bound)
	{
		cerr << "GLFramebuffer: Bind() called, but framebuffer was already bound" << endl;
		return;
	}

	// Store old viewport
	glPushAttrib(GL_VIEWPORT_BIT);
	// Bind FBO
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id);
	// Set viewport
	glViewport(0, 0, width, height);
	bound = true;
#ifndef NDEBUG
	GLUtility::CheckOpenGLError("GLFramebuffer: Bind()");
#endif
}

// ----------------------------------------------------------------------------
void GLFramebuffer::Unbind()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

	if (bound)
	{
		// Restore viewport
		glPopAttrib();
	}
	else
	{
		cerr << "GLFramebuffer: Unbind() called, but framebuffer was not bound" << endl;
	}

	bound = false;

#ifndef NDEBUG
	GLUtility::CheckOpenGLError("GLFramebuffer: Unbind()");
#endif
}

// ----------------------------------------------------------------------------
int GLFramebuffer::GetStatus()
{
	if (!bound) Bind();
	return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::IsOk()
{
	int status = GetStatus();
	switch (status)
	{
		case GL_FRAMEBUFFER_COMPLETE_EXT:
			return true;
			break;
		case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
			return false;
			break;
		default:
			//assert(false); // Error in framebuffer code!
			return false;
			break;
	}
}

// ----------------------------------------------------------------------------
GLTexture* GLFramebuffer::GetTexture2D(int attachment)
{
	// Look up the texture, return 0 if nothing's attached
	map<int, GLRendertarget*>::iterator atit = attachments.find(attachment);
	if (atit == attachments.end()) return 0;
	GLRenderTexture2D *rt = dynamic_cast<GLRenderTexture2D*>(atit->second);
	if (!rt) return 0;
	// Return texture
	return rt->GetTexture();
}

// ----------------------------------------------------------------------------
const GLTexture* GLFramebuffer::GetTexture2D(int attachment) const
{
	// Look up the texture, return 0 if nothing's attached
	map<int, GLRendertarget*>::const_iterator atit = attachments.find(attachment);
	if (atit == attachments.end()) return 0;
	const GLRenderTexture2D *rt = dynamic_cast<const GLRenderTexture2D*>(atit->second);
	if (!rt) return 0;
	// Return texture
	return rt->GetTexture();
}

// ----------------------------------------------------------------------------
bool GLFramebuffer::Resize(int width, int height)
{
	// Resize all attachments
	for (map<int, GLRendertarget*>::iterator i = attachments.begin(); i != attachments.end(); )
	{
		int attachment = i->first;
		i++;
		// We need to detach, because the internal rendertarget might change
		GLRendertarget *rt = DetachRendertarget(attachment);
		if (!rt->Resize(width, height))
		{
			cerr << "GLFrameBuffer: Resize failed for attachment " << attachment << endl;
			delete rt;
			return false;
		}
		// Re-attach the rendertarget
		AttachRendertarget(attachment, *rt);
	}

	// Update framebuffer size
	this->width = width;
	this->height = height;

	// Unbind the framebuffer if bound
	if (bound) Unbind();

	return true;
}
<|endoftext|>


<commit_before>
#include <NdbApi.hpp>
#include <NdbOut.hpp>
#include <NdbTick.h>

struct
S_Scan {
  const char * m_table;
  const char * m_index;
  NdbIndexScanOperation * m_scan;
  NdbResultSet * m_result;
  Uint32 metaid;
  Uint32 match_count;
  Uint32 row_count;
};

static S_Scan g_scans[] = {
  { "affiliatestometa", "ind_affiliatestometa", 0, 0, 0, 0, 0 },
  { "media", "metaid", 0, 0, 0, 0, 0 },
  { "meta", "PRIMARY", 0, 0, 0, 0, 0 },
  { "artiststometamap", "PRIMARY", 0, 0, 0, 0, 0 },
  { "subgenrestometamap", "metaid", 0, 0, 0, 0, 0 }
};

#define require(x) if(!(x)) { ndbout << "LINE: " << __LINE__ << endl;abort(); }
#define require2(o, x) if(!(x)) { ndbout << o->getNdbError() << endl; abort(); }
Uint32 g_affiliateid = 2;
Uint32 g_formatids[] = { 8, 31, 76 };

Uint64 start;
Uint32 g_artistid = 0;
Uint32 g_subgenreid = 0;

NdbConnection* g_trans =  0;
static void lookup();

int
main(void){
  Ndb g_ndb("test");
  g_ndb.init(1024);

  require(g_ndb.waitUntilReady() == 0);

  g_trans = g_ndb.startTransaction();
  require(g_trans);

  size_t i, j;
  const size_t cnt = sizeof(g_scans)/sizeof(g_scans[0]);

  start = NdbTick_CurrentMillisecond();

  for(i = 0; i<cnt; i++){
    ndbout_c("starting scan on: %s %s",
	     g_scans[i].m_table, g_scans[i].m_index);
    g_scans[i].m_scan = g_trans->getNdbIndexScanOperation(g_scans[i].m_index,
							  g_scans[i].m_table);
    NdbIndexScanOperation* scan = g_scans[i].m_scan;
    require(scan);
    g_scans[i].m_result = scan->readTuples(NdbScanOperation::LM_CommittedRead,
					   0, 0, true);
    require(g_scans[i].m_result);
  }

  require(!g_scans[0].m_scan->setBound((Uint32)0,
				       NdbIndexScanOperation::BoundEQ,
				       &g_affiliateid,
				       sizeof(g_affiliateid)));
#if 0
  require(!g_scans[1].m_scan->setBound((Uint32)0,
				       NdbIndexScanOperation::BoundLE,
				       &g_formatids[0],
				       sizeof(g_formatids[0])));
#endif

  NdbScanFilter sf(g_scans[1].m_scan);
  sf.begin(NdbScanFilter::OR);
  sf.eq(2, g_formatids[0]);
  sf.eq(2, g_formatids[1]);
  sf.eq(2, g_formatids[2]);
  sf.end();

  // affiliatestometa
  require(g_scans[0].m_scan->getValue("uniquekey"));
  require(g_scans[0].m_scan->getValue("xml"));

  // media
  require(g_scans[1].m_scan->getValue("path"));
  require(g_scans[1].m_scan->getValue("mediaid"));
  require(g_scans[1].m_scan->getValue("formatid"));

  // meta
  require(g_scans[2].m_scan->getValue("name"));
  require(g_scans[2].m_scan->getValue("xml"));

  // artiststometamap
  require(g_scans[3].m_scan->getValue("artistid", (char*)&g_artistid));

  // subgenrestometamap
  require(g_scans[4].m_scan->getValue("subgenreid", (char*)&g_subgenreid));

  for(i = 0; i<cnt; i++){
    g_scans[i].m_scan->getValue("metaid", (char*)&g_scans[i].metaid);
  }

  g_trans->execute(NoCommit, AbortOnError, 1);

  Uint32 max_val = 0;
  Uint32 match_val = 0;

  S_Scan * F [5], * Q [5], * nextF [5];
  Uint32 F_sz = 0, Q_sz = 0;
  for(i = 0; i<cnt; i++){
    F_sz++;
    F[i] = &g_scans[i];
  }

  Uint32 match_count = 0;
  while(F_sz > 0){
    Uint32 prev_F_sz = F_sz;
    F_sz = 0;
    bool found = false;
    //for(i = 0; i<cnt; i++)
    //ndbout_c("%s - %d", g_scans[i].m_table, g_scans[i].metaid);

    for(i = 0; i<prev_F_sz; i++){
      int res = F[i]->m_result->nextResult();
      if(res == -1)
	abort();

      if(res == 1){
	continue;
      }

      Uint32 metaid = F[i]->metaid;
      F[i]->row_count++;

      if(metaid == match_val){
	//ndbout_c("flera");
	nextF[F_sz++] = F[i];
	require(F_sz >= 0 && F_sz <= cnt);
	F[i]->match_count++;
	Uint32 comb = 1;
	for(j = 0; j<cnt; j++){
	  comb *= (&g_scans[j] == F[i] ? 1 : g_scans[j].match_count);
	}
	match_count += comb;
	found = true;
	continue;
      }
      if(metaid < max_val){
	nextF[F_sz++] = F[i];
	require(F_sz >= 0 && F_sz <= cnt);
	continue;
      }
      if(metaid > max_val){
	for(j = 0; j<Q_sz; j++)
	  nextF[F_sz++] = Q[j];
	require(F_sz >= 0 && F_sz <= cnt);
	Q_sz = 0;
	max_val = metaid;
      }
      Q[Q_sz++] = F[i];
      require(Q_sz >= 0 && Q_sz <= cnt);
    }
    if(F_sz == 0 && Q_sz > 0){
      match_val = max_val;
      for(j = 0; j<Q_sz; j++){
	nextF[F_sz++] = Q[j];
	Q[j]->match_count = 1;
      }
      require(F_sz >= 0 && F_sz <= cnt);
      require(Q_sz >= 0 && Q_sz <= cnt);
      Q_sz = 0;
      match_count++;
      lookup();
    } else if(!found && F_sz + Q_sz < cnt){
      F_sz = 0;
    }
    require(F_sz >= 0 && F_sz <= cnt);
    for(i = 0; i<F_sz; i++)
      F[i] = nextF[i];
  }

  start = NdbTick_CurrentMillisecond() - start;
  ndbout_c("Elapsed: %lldms", start);

  ndbout_c("rows: %d", match_count);
  for(i = 0; i<cnt; i++){
    ndbout_c("%s : %d", g_scans[i].m_table, g_scans[i].row_count);
  }
}

static
void
lookup(){
  {
    NdbOperation* op = g_trans->getNdbOperation("artists");
    require2(g_trans, op);
    require2(op, op->readTuple() == 0);
    require2(op, op->equal("artistid", g_artistid) == 0);
    require2(op, op->getValue("name"));
  }

  {
    NdbOperation* op = g_trans->getNdbOperation("subgenres");
    require2(g_trans, op);
    require2(op, op->readTuple() == 0);
    require2(op, op->equal("subgenreid", g_subgenreid) == 0);
    require2(op, op->getValue("name"));
  }

  static int loop = 0;
  if(loop++ >= 16){
    loop = 0;
    require(g_trans->execute(NoCommit) == 0);
  }
  //require(g_trans->restart() == 0);
}
<commit_msg>run in loop<commit_after>
#include <NdbApi.hpp>
#include <NdbOut.hpp>
#include <NdbTick.h>

struct
S_Scan {
  const char * m_table;
  const char * m_index;
  NdbIndexScanOperation * m_scan;
  NdbResultSet * m_result;
  Uint32 metaid;
  Uint32 match_count;
  Uint32 row_count;
};

static S_Scan g_scans[] = {
  { "affiliatestometa", "ind_affiliatestometa", 0, 0, 0, 0, 0 },
  { "media", "metaid", 0, 0, 0, 0, 0 },
  { "meta", "PRIMARY", 0, 0, 0, 0, 0 },
  { "artiststometamap", "PRIMARY", 0, 0, 0, 0, 0 },
  { "subgenrestometamap", "metaid", 0, 0, 0, 0, 0 }
};

#define require(x) if(!(x)) { ndbout << "LINE: " << __LINE__ << endl;abort(); }
#define require2(o, x) if(!(x)) { ndbout << o->getNdbError() << endl; abort(); }
Uint32 g_affiliateid = 2;
Uint32 g_formatids[] = { 8, 31, 76 };

Uint64 start;
Uint32 g_artistid = 0;
Uint32 g_subgenreid = 0;

NdbConnection* g_trans =  0;
static void lookup();

int
main(void){
  Ndb g_ndb("test");
  g_ndb.init(1024);

  require(g_ndb.waitUntilReady() == 0);

  while(true){
    g_trans = g_ndb.startTransaction();
    require(g_trans);

    size_t i, j;
    const size_t cnt = sizeof(g_scans)/sizeof(g_scans[0]);

    start = NdbTick_CurrentMillisecond();

    for(i = 0; i<cnt; i++){
      ndbout_c("starting scan on: %s %s",
	       g_scans[i].m_table, g_scans[i].m_index);
      g_scans[i].m_scan = g_trans->getNdbIndexScanOperation(g_scans[i].m_index,
							    g_scans[i].m_table);
      NdbIndexScanOperation* scan = g_scans[i].m_scan;
      require(scan);
      g_scans[i].m_result = scan->readTuples(NdbScanOperation::LM_CommittedRead,
					     0, 0, true);
      require(g_scans[i].m_result);
    }

    require(!g_scans[0].m_scan->setBound((Uint32)0,
					 NdbIndexScanOperation::BoundEQ,
					 &g_affiliateid,
					 sizeof(g_affiliateid)));
#if 0
    require(!g_scans[1].m_scan->setBound((Uint32)0,
					 NdbIndexScanOperation::BoundLE,
					 &g_formatids[0],
					 sizeof(g_formatids[0])));
#endif

    NdbScanFilter sf(g_scans[1].m_scan);
    sf.begin(NdbScanFilter::OR);
    sf.eq(2, g_formatids[0]);
    sf.eq(2, g_formatids[1]);
    sf.eq(2, g_formatids[2]);
    sf.end();

    // affiliatestometa
    require(g_scans[0].m_scan->getValue("uniquekey"));
    require(g_scans[0].m_scan->getValue("xml"));

    // media
    require(g_scans[1].m_scan->getValue("path"));
    require(g_scans[1].m_scan->getValue("mediaid"));
    require(g_scans[1].m_scan->getValue("formatid"));

    // meta
    require(g_scans[2].m_scan->getValue("name"));
    require(g_scans[2].m_scan->getValue("xml"));

    // artiststometamap
    require(g_scans[3].m_scan->getValue("artistid", (char*)&g_artistid));

    // subgenrestometamap
    require(g_scans[4].m_scan->getValue("subgenreid", (char*)&g_subgenreid));

    for(i = 0; i<cnt; i++){
      g_scans[i].m_scan->getValue("metaid", (char*)&g_scans[i].metaid);
    }

    g_trans->execute(NoCommit, AbortOnError, 1);

    Uint32 max_val = 0;
    Uint32 match_val = 0;

    S_Scan * F [5], * Q [5], * nextF [5];
    Uint32 F_sz = 0, Q_sz = 0;
    for(i = 0; i<cnt; i++){
      F_sz++;
      F[i] = &g_scans[i];
    }

    Uint32 match_count = 0;
    while(F_sz > 0){
      Uint32 prev_F_sz = F_sz;
      F_sz = 0;
      bool found = false;
      //for(i = 0; i<cnt; i++)
      //ndbout_c("%s - %d", g_scans[i].m_table, g_scans[i].metaid);

      for(i = 0; i<prev_F_sz; i++){
	int res = F[i]->m_result->nextResult();
	if(res == -1)
	  abort();

	if(res == 1){
	  continue;
	}

	Uint32 metaid = F[i]->metaid;
	F[i]->row_count++;

	if(metaid == match_val){
	  //ndbout_c("flera");
	  nextF[F_sz++] = F[i];
	  require(F_sz >= 0 && F_sz <= cnt);
	  F[i]->match_count++;
	  Uint32 comb = 1;
	  for(j = 0; j<cnt; j++){
	    comb *= (&g_scans[j] == F[i] ? 1 : g_scans[j].match_count);
	  }
	  match_count += comb;
	  found = true;
	  continue;
	}
	if(metaid < max_val){
	  nextF[F_sz++] = F[i];
	  require(F_sz >= 0 && F_sz <= cnt);
	  continue;
	}
	if(metaid > max_val){
	  for(j = 0; j<Q_sz; j++)
	    nextF[F_sz++] = Q[j];
	  require(F_sz >= 0 && F_sz <= cnt);
	  Q_sz = 0;
	  max_val = metaid;
	}
	Q[Q_sz++] = F[i];
	require(Q_sz >= 0 && Q_sz <= cnt);
      }
      if(F_sz == 0 && Q_sz > 0){
	match_val = max_val;
	for(j = 0; j<Q_sz; j++){
	  nextF[F_sz++] = Q[j];
	  Q[j]->match_count = 1;
	}
	require(F_sz >= 0 && F_sz <= cnt);
	require(Q_sz >= 0 && Q_sz <= cnt);
	Q_sz = 0;
	match_count++;
	lookup();
      } else if(!found && F_sz + Q_sz < cnt){
	F_sz = 0;
      }
      require(F_sz >= 0 && F_sz <= cnt);
      for(i = 0; i<F_sz; i++)
	F[i] = nextF[i];
    }

    start = NdbTick_CurrentMillisecond() - start;
    ndbout_c("Elapsed: %lldms", start);

    ndbout_c("rows: %d", match_count);
    for(i = 0; i<cnt; i++){
      ndbout_c("%s : %d", g_scans[i].m_table, g_scans[i].row_count);
    }
    g_trans->close();
  }
}

static
void
lookup(){
  {
    NdbOperation* op = g_trans->getNdbOperation("artists");
    require2(g_trans, op);
    require2(op, op->readTuple() == 0);
    require2(op, op->equal("artistid", g_artistid) == 0);
    require2(op, op->getValue("name"));
  }

  {
    NdbOperation* op = g_trans->getNdbOperation("subgenres");
    require2(g_trans, op);
    require2(op, op->readTuple() == 0);
    require2(op, op->equal("subgenreid", g_subgenreid) == 0);
    require2(op, op->getValue("name"));
  }

  static int loop = 0;
  if(loop++ >= 16){
    loop = 0;
    require(g_trans->execute(NoCommit) == 0);
  }
  //require(g_trans->restart() == 0);
}
<|endoftext|>


<commit_before>/* $Id$ */
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

/*
$begin ad_input.cpp$$
$spell
	Cpp
	cstddef
$$

$section AD Output Operator: Example and Test$$

$index <<, AD example$$
$index input, AD example$$
$index example, AD input$$
$index test, AD input$$

$code
$verbatim%example/ad_input.cpp%0%// BEGIN C++%// END C++%1%$$
$$

$end
*/
// BEGIN C++

# include <cppad/cppad.hpp>

# include <sstream>  // std::istringstream
# include <string>   // std::string

bool ad_input(void)
{	bool ok = true;

	std::string str ("123 456");
	std::istringstream is(str);

	CppAD::AD<double> x(1.), y(2.);

	is >> x >> y;

	ok &= (x == 123.);
	ok &= (y == 456.);

	return ok;
}
// END C++
<commit_msg>ad_input.cpp: Show, by example, result of input is a parameter.<commit_after>/* $Id$ */
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

/*
$begin ad_input.cpp$$
$spell
	Cpp
	cstddef
$$

$section AD Output Operator: Example and Test$$

$index <<, AD example$$
$index input, AD example$$
$index example, AD input$$
$index test, AD input$$

$code
$verbatim%example/ad_input.cpp%0%// BEGIN C++%// END C++%1%$$
$$

$end
*/
// BEGIN C++

# include <cppad/cppad.hpp>

# include <sstream>  // std::istringstream
# include <string>   // std::string

bool ad_input(void)
{	bool ok = true;

	// create the input string stream is.
	std::string str ("123 456");
	std::istringstream is(str);

	// start and AD<double> recording
	CPPAD_TESTVECTOR( CppAD::AD<double> ) x(1), y(1);
	x[0] = 1.0;
	CppAD::Independent(x);
	CppAD::AD<double> z = x[0];
	ok &= Variable(z);

	// read first number into z and second into y[0]
	is >> z >> y[0];
	ok   &= Parameter(z);
	ok   &= (z == 123.);
	ok   &= Parameter(y[0]);
	ok   &= (y[0] == 456.);
	//
	// terminate recording starting by call to Independent
	CppAD::ADFun<double> f(x, y);

	return ok;
}
// END C++
<|endoftext|>


<commit_before>#pragma once
// Project specific
#include <AudioHandler.hpp>
#include <Doremi/Core/Include/InputHandler.hpp>
#include <Doremi/Core/Include/InputHandlerClient.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
//#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <EntityComponent/EntityHandler.hpp>
#include <DoremiEngine/Audio/Include/AudioModule.hpp>
#include <iostream>
#include <PlayerHandler.hpp>
#include <FrequencyBufferHandler.hpp>

// Events
#include <EventHandler/EventHandler.hpp>
#include <EventHandler/Events/ChangeMenuState.hpp>

// Logging
#include <DoremiEngine/Logging/Include/LoggingModule.hpp>
#include <DoremiEngine/Logging/Include/SubmoduleManager.hpp>
#include <DoremiEngine/Logging/Include/Logger/Logger.hpp>

// Timing
#include <DoremiEngine/Timing/Include/Measurement/TimeMeasurementManager.hpp>

namespace Doremi
{
    namespace Core
    {
        AudioHandler::AudioHandler(const DoremiEngine::Core::SharedContext& p_sharedContext) : m_sharedContext(p_sharedContext), m_logger(nullptr)
        {
            m_logger = &m_sharedContext.GetLoggingModule().GetSubModuleManager().GetLogger();

            m_currentFrequency = 0;
            /* 99999 is a default "error" value. It is used to create a new channel in module. We send the channelID to the module and if it is 99999
            it is treated as uninitialized This has been fixed. 999999 is now -1
            and starts a new channel that is returned to the variable.*/
            m_continuousFrequencyAnalyserChannelID = -1;
            m_continuousFrequencyAnalyserSoundID = 0;
            m_repeatableFrequencyAnalyserChannelID = -1;
            m_repeatableFrequencyAnalyserSoundID = 0;
            m_outputRepeatableSoundChannelID = -1;
            m_outputRepeatableSoundID = 0;
            m_accumulatedDeltaTime = 0;
            m_repeatableAnalysisComplete = false;
            m_frequencyVectorPrecision = 0.01f;
            m_timeGunReloadButtonWasPressed = 0.0f;

            // Load the background sounds
            m_backgroundSounds[BackgroundSound::InGameMainTheme] = m_sharedContext.GetAudioModule().LoadSound("Sounds/BackgroundGame.wav", 0.5, 5000);
            EventHandler::GetInstance()->Subscribe(EventType::ChangeMenuState, this);
        }

        AudioHandler::~AudioHandler()
        {
            // Do not delete m_logger, internally handled by loggingmodule
        }

        void AudioHandler::StartAudioHandler(const DoremiEngine::Core::SharedContext& p_sharedContext)
        {
            if(m_singleton == nullptr)
            {
                m_singleton = new AudioHandler(p_sharedContext);
            }
        }

        void AudioHandler::StopAudioHandler()
        {
            delete m_singleton;
            m_singleton = nullptr;
        }

        void AudioHandler::Initialize() {}

        AudioHandler* AudioHandler::m_singleton = nullptr;

        AudioHandler* AudioHandler::GetInstance() { return m_singleton; }

        void AudioHandler::SetGunButtonDownTime(double p_time) { m_timeGunReloadButtonWasPressed = p_time; }

        void AudioHandler::SetupContinuousRecording()
        {
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            m_continuousFrequencyAnalyserSoundID = t_audioModule.SetupRecording(true);
        }

        void AudioHandler::SetupRepeatableRecording()
        {
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            m_repeatableFrequencyAnalyserSoundID = t_audioModule.SetupRecording(false);
        }

        void AudioHandler::StartContinuousRecording()
        {
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            t_audioModule.StopRecording();
            t_audioModule.StartRecording(m_continuousFrequencyAnalyserSoundID, true);
            m_SoundState = HOLDCONTINUOUSANALYSIS;
        }

        void AudioHandler::StartRepeatableRecording()
        {
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            t_audioModule.StopRecording();
            m_currentFrequency = 0;
            t_audioModule.StartRecording(m_repeatableFrequencyAnalyserSoundID, false); /**TODOLH Behvs stop  start recording?*/
            // t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID,
            // 0.0f); /**TODOLH Detta setvolume p recordkanalernas playback knns inte optimalt. Revisit maybe*/
            m_SoundState = HOLDREPEATABLEANALYSIS;
            m_repeatableAnalysisComplete = false;
        }

        float AudioHandler::GetRepeatableSoundFrequency()
        {
            TIME_FUNCTION_START
            // Make sure that the analysis is complete otherwise m_frequencies wont be filled and we can get index out of range
            if(m_repeatableAnalysisComplete)
            {
                // Get the audiomodule
                DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
                // check how far into the sound that the repeatable sound is in milliseconds
                double t_timeElapsed = t_audioModule.GetSoundTimePointer(m_outputRepeatableSoundChannelID);
                // Get the full lenght of the sound in milliseconds
                double t_soundLength = t_audioModule.GetSoundLength(m_outputRepeatableSoundID);
                // Calculate how far into the sound that the pointer is. Percentual
                double t_percentualPosition = t_timeElapsed / t_soundLength;
                // Get the full range of the vector
                double t_size = static_cast<double>(m_frequencies.size() - 1);
                // Calculate where in the array we should access the frequency
                int arrayPosition = static_cast<int>(t_size * t_percentualPosition);
                // Get the frequency
                float retValue = m_frequencies[arrayPosition];
                TIME_FUNCTION_STOP
                return retValue;
            }
            else
            {
                TIME_FUNCTION_STOP
                return 0;
            }
        }

        void AudioHandler::PlayRepeatableRecordedSound()
        {
            // This is a dangerous function since soundID starts at 0. If there is no sound on 0 we will crash
            if(m_SoundState != HOLDREPEATABLEANALYSIS && m_SoundState != ANALYSEREPEATABLE)
            {
                DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
                t_audioModule.PlayASound(m_outputRepeatableSoundID, false, m_outputRepeatableSoundChannelID);
            }
        }

        void AudioHandler::Update(double p_deltaTime)
        {
            TIME_FUNCTION_START
            unsigned int recordPointer;
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            switch(m_SoundState)
            {
                case Doremi::Core::AudioHandler::ANALYSECONTINUOUS:
                    m_currentFrequency = t_audioModule.AnalyseSoundSpectrum(m_continuousFrequencyAnalyserChannelID);
                    break;

                case Doremi::Core::AudioHandler::HOLDCONTINUOUSANALYSIS:
                    recordPointer = t_audioModule.GetRecordPointer();
                    // kollar s att vi har spelat in en bit innan vi startar analysen. Om man startar analysen Dirr buggar det ut.
                    if(recordPointer > 9600)
                    {
                        m_SoundState = ANALYSECONTINUOUS;
                        // Default vrde som inte kan anvndas. I komponenterna stts det i defaultkontruktorn.
                        if(m_continuousFrequencyAnalyserChannelID != -1)
                        {
                            /**
                            TODOLH Behvs nog uppdatera ljudposition till listener position.
                            */
                            t_audioModule.PlaySoundOnSpecificChannel(m_continuousFrequencyAnalyserSoundID, true, m_continuousFrequencyAnalyserChannelID);
                            t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 0.0f);
                        }
                        else
                        {
                            t_audioModule.PlayASound(m_continuousFrequencyAnalyserSoundID, true, m_continuousFrequencyAnalyserChannelID);
                            t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 0.0f);
                        }
                        t_audioModule.SetPriority(m_continuousFrequencyAnalyserChannelID, 0);
                        /** TODOLH osker p om detta behvs.
                        Tydligen kan det bli s att fmod snor kanaler. Men d tar den kanaler som har lg prio*/
                    }
                    break;

                case Doremi::Core::AudioHandler::ANALYSEREPEATABLE:
                    recordPointer = t_audioModule.GetRecordPointer();
                    // Kolla om ljudet r "klart" isfall verg till andra inspelingssttet.
                    if(!t_audioModule.IsRecording())
                    {
                        m_SoundState = HOLDCONTINUOUSANALYSIS;
                        m_repeatableAnalysisComplete = true;
                        t_audioModule.StopRecording();
                        t_audioModule.StartRecording(m_continuousFrequencyAnalyserSoundID, true);
                        t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 1.0f);
                        m_outputRepeatableSoundID =
                            t_audioModule.CopySound(m_repeatableFrequencyAnalyserSoundID, m_outputRepeatableSoundID, m_timeGunReloadButtonWasPressed);
                        t_audioModule.PlayASound(m_outputRepeatableSoundID, false, m_outputRepeatableSoundChannelID);
                        t_audioModule.SetVolumeOnChannel(m_outputRepeatableSoundChannelID, 0);
                    }
                    else
                    {
                        // Fixa in i array fr att anvndas med beamen senare!
                        m_accumulatedDeltaTime += p_deltaTime;
                        if(m_accumulatedDeltaTime > m_frequencyVectorPrecision)
                        {
                            m_accumulatedDeltaTime = 0; /// Ta tidsintervallet multiplicera med m_frequencyVectorPrecision  ta det arrayvrdet!!
                            m_frequencies.push_back(t_audioModule.AnalyseSoundSpectrum(m_repeatableFrequencyAnalyserChannelID));
                        }
                        else
                        {
                            // do nothing
                        }
                    }
                    break;
                case Doremi::Core::AudioHandler::HOLDREPEATABLEANALYSIS:
                    recordPointer = t_audioModule.GetRecordPointer();
                    // kollar s att vi har spelat in en bit innan vi startar analysen. Om man startar analysen Dirr buggar det ut. TODOLH Definea
                    // 9600 kanske?
                    if(recordPointer > 9600)
                    {
                        m_SoundState = ANALYSEREPEATABLE;
                        m_frequencies.clear();
                        t_audioModule.PlayASound(m_repeatableFrequencyAnalyserSoundID, false, m_repeatableFrequencyAnalyserChannelID);
                        t_audioModule.SetVolumeOnChannel(m_repeatableFrequencyAnalyserChannelID, 0.0f);
                        t_audioModule.SetPriority(m_repeatableFrequencyAnalyserChannelID, 1);
                    }
                    break;
                default:
                    break;
            }

            InputHandlerClient* inputHandler = (InputHandlerClient*)PlayerHandler::GetInstance()->GetDefaultInputHandler();
            if(inputHandler != nullptr)
            {

                if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency0))
                {
                    m_currentFrequency = 0;
                }
                else if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency500))
                {
                    m_currentFrequency = 500;
                }
                else if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency1000))
                {
                    m_currentFrequency = 1000;
                }
            }
            // Send frequence to buffer
            FrequencyBufferHandler* freqBufferHandler = PlayerHandler::GetInstance()->GetDefaultFrequencyBufferHandler();
            if(freqBufferHandler != nullptr)
            {
                freqBufferHandler->BufferFrequency(m_currentFrequency);
                using namespace Doremi::Utilities::Logging;
                m_logger->DebugLog(LogTag::AUDIO, LogLevel::MASS_DATA_PRINT, "F, %f", m_currentFrequency);
            }

            TIME_FUNCTION_STOP
        }

        void AudioHandler::OnEvent(Event* p_event)
        {
            if(p_event->eventType == EventType::ChangeMenuState)
            {
                ChangeMenuState* t_stateEvent = static_cast<ChangeMenuState*>(p_event);

                if(t_stateEvent->state == DoremiStates::RUNGAME)
                {
                    DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
                    t_audioModule.PlayASound(m_backgroundSounds[BackgroundSound::InGameMainTheme], true, m_backgroundChannelId);
                }
            }
        }
    }
}
<commit_msg>Error check on map<commit_after>#pragma once
// Project specific
#include <AudioHandler.hpp>
#include <Doremi/Core/Include/InputHandler.hpp>
#include <Doremi/Core/Include/InputHandlerClient.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
//#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <EntityComponent/EntityHandler.hpp>
#include <DoremiEngine/Audio/Include/AudioModule.hpp>
#include <iostream>
#include <PlayerHandler.hpp>
#include <FrequencyBufferHandler.hpp>

// Events
#include <EventHandler/EventHandler.hpp>
#include <EventHandler/Events/ChangeMenuState.hpp>

// Logging
#include <DoremiEngine/Logging/Include/LoggingModule.hpp>
#include <DoremiEngine/Logging/Include/SubmoduleManager.hpp>
#include <DoremiEngine/Logging/Include/Logger/Logger.hpp>

// Timing
#include <DoremiEngine/Timing/Include/Measurement/TimeMeasurementManager.hpp>

namespace Doremi
{
    namespace Core
    {
        AudioHandler::AudioHandler(const DoremiEngine::Core::SharedContext& p_sharedContext) : m_sharedContext(p_sharedContext), m_logger(nullptr)
        {
            m_logger = &m_sharedContext.GetLoggingModule().GetSubModuleManager().GetLogger();

            m_currentFrequency = 0;
            /* 99999 is a default "error" value. It is used to create a new channel in module. We send the channelID to the module and if it is 99999
            it is treated as uninitialized This has been fixed. 999999 is now -1
            and starts a new channel that is returned to the variable.*/
            m_continuousFrequencyAnalyserChannelID = -1;
            m_continuousFrequencyAnalyserSoundID = 0;
            m_repeatableFrequencyAnalyserChannelID = -1;
            m_repeatableFrequencyAnalyserSoundID = 0;
            m_outputRepeatableSoundChannelID = -1;
            m_outputRepeatableSoundID = 0;
            m_accumulatedDeltaTime = 0;
            m_repeatableAnalysisComplete = false;
            m_frequencyVectorPrecision = 0.01f;
            m_timeGunReloadButtonWasPressed = 0.0f;

            // Load the background sounds
            m_backgroundSounds[BackgroundSound::InGameMainTheme] = m_sharedContext.GetAudioModule().LoadSound("Sounds/BackgroundGame.wav", 0.5, 5000);
            EventHandler::GetInstance()->Subscribe(EventType::ChangeMenuState, this);
        }

        AudioHandler::~AudioHandler()
        {
            // Do not delete m_logger, internally handled by loggingmodule
        }

        void AudioHandler::StartAudioHandler(const DoremiEngine::Core::SharedContext& p_sharedContext)
        {
            if(m_singleton == nullptr)
            {
                m_singleton = new AudioHandler(p_sharedContext);
            }
        }

        void AudioHandler::StopAudioHandler()
        {
            delete m_singleton;
            m_singleton = nullptr;
        }

        void AudioHandler::Initialize() {}

        AudioHandler* AudioHandler::m_singleton = nullptr;

        AudioHandler* AudioHandler::GetInstance() { return m_singleton; }

        void AudioHandler::SetGunButtonDownTime(double p_time) { m_timeGunReloadButtonWasPressed = p_time; }

        void AudioHandler::SetupContinuousRecording()
        {
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            m_continuousFrequencyAnalyserSoundID = t_audioModule.SetupRecording(true);
        }

        void AudioHandler::SetupRepeatableRecording()
        {
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            m_repeatableFrequencyAnalyserSoundID = t_audioModule.SetupRecording(false);
        }

        void AudioHandler::StartContinuousRecording()
        {
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            t_audioModule.StopRecording();
            t_audioModule.StartRecording(m_continuousFrequencyAnalyserSoundID, true);
            m_SoundState = HOLDCONTINUOUSANALYSIS;
        }

        void AudioHandler::StartRepeatableRecording()
        {
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            t_audioModule.StopRecording();
            m_currentFrequency = 0;
            t_audioModule.StartRecording(m_repeatableFrequencyAnalyserSoundID, false); /**TODOLH Behvs stop  start recording?*/
            // t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID,
            // 0.0f); /**TODOLH Detta setvolume p recordkanalernas playback knns inte optimalt. Revisit maybe*/
            m_SoundState = HOLDREPEATABLEANALYSIS;
            m_repeatableAnalysisComplete = false;
        }

        float AudioHandler::GetRepeatableSoundFrequency()
        {
            TIME_FUNCTION_START
            // Make sure that the analysis is complete otherwise m_frequencies wont be filled and we can get index out of range
            if(m_repeatableAnalysisComplete)
            {
                // Get the audiomodule
                DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
                // check how far into the sound that the repeatable sound is in milliseconds
                double t_timeElapsed = t_audioModule.GetSoundTimePointer(m_outputRepeatableSoundChannelID);
                // Get the full lenght of the sound in milliseconds
                double t_soundLength = t_audioModule.GetSoundLength(m_outputRepeatableSoundID);
                // Calculate how far into the sound that the pointer is. Percentual
                double t_percentualPosition = t_timeElapsed / t_soundLength;
                // Get the full range of the vector
                double t_size = static_cast<double>(m_frequencies.size() - 1);
                // Calculate where in the array we should access the frequency
                int arrayPosition = static_cast<int>(t_size * t_percentualPosition);
                // Get the frequency
                float retValue = m_frequencies[arrayPosition];
                TIME_FUNCTION_STOP
                return retValue;
            }
            else
            {
                TIME_FUNCTION_STOP
                return 0;
            }
        }

        void AudioHandler::PlayRepeatableRecordedSound()
        {
            // This is a dangerous function since soundID starts at 0. If there is no sound on 0 we will crash
            if(m_SoundState != HOLDREPEATABLEANALYSIS && m_SoundState != ANALYSEREPEATABLE)
            {
                DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
                t_audioModule.PlayASound(m_outputRepeatableSoundID, false, m_outputRepeatableSoundChannelID);
            }
        }

        void AudioHandler::Update(double p_deltaTime)
        {
            TIME_FUNCTION_START
            unsigned int recordPointer;
            DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
            switch(m_SoundState)
            {
                case Doremi::Core::AudioHandler::ANALYSECONTINUOUS:
                    m_currentFrequency = t_audioModule.AnalyseSoundSpectrum(m_continuousFrequencyAnalyserChannelID);
                    break;

                case Doremi::Core::AudioHandler::HOLDCONTINUOUSANALYSIS:
                    recordPointer = t_audioModule.GetRecordPointer();
                    // kollar s att vi har spelat in en bit innan vi startar analysen. Om man startar analysen Dirr buggar det ut.
                    if(recordPointer > 9600)
                    {
                        m_SoundState = ANALYSECONTINUOUS;
                        // Default vrde som inte kan anvndas. I komponenterna stts det i defaultkontruktorn.
                        if(m_continuousFrequencyAnalyserChannelID != -1)
                        {
                            /**
                            TODOLH Behvs nog uppdatera ljudposition till listener position.
                            */
                            t_audioModule.PlaySoundOnSpecificChannel(m_continuousFrequencyAnalyserSoundID, true, m_continuousFrequencyAnalyserChannelID);
                            t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 0.0f);
                        }
                        else
                        {
                            t_audioModule.PlayASound(m_continuousFrequencyAnalyserSoundID, true, m_continuousFrequencyAnalyserChannelID);
                            t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 0.0f);
                        }
                        t_audioModule.SetPriority(m_continuousFrequencyAnalyserChannelID, 0);
                        /** TODOLH osker p om detta behvs.
                        Tydligen kan det bli s att fmod snor kanaler. Men d tar den kanaler som har lg prio*/
                    }
                    break;

                case Doremi::Core::AudioHandler::ANALYSEREPEATABLE:
                    recordPointer = t_audioModule.GetRecordPointer();
                    // Kolla om ljudet r "klart" isfall verg till andra inspelingssttet.
                    if(!t_audioModule.IsRecording())
                    {
                        m_SoundState = HOLDCONTINUOUSANALYSIS;
                        m_repeatableAnalysisComplete = true;
                        t_audioModule.StopRecording();
                        t_audioModule.StartRecording(m_continuousFrequencyAnalyserSoundID, true);
                        t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 1.0f);
                        m_outputRepeatableSoundID =
                            t_audioModule.CopySound(m_repeatableFrequencyAnalyserSoundID, m_outputRepeatableSoundID, m_timeGunReloadButtonWasPressed);
                        t_audioModule.PlayASound(m_outputRepeatableSoundID, false, m_outputRepeatableSoundChannelID);
                        t_audioModule.SetVolumeOnChannel(m_outputRepeatableSoundChannelID, 0);
                    }
                    else
                    {
                        // Fixa in i array fr att anvndas med beamen senare!
                        m_accumulatedDeltaTime += p_deltaTime;
                        if(m_accumulatedDeltaTime > m_frequencyVectorPrecision)
                        {
                            m_accumulatedDeltaTime = 0; /// Ta tidsintervallet multiplicera med m_frequencyVectorPrecision  ta det arrayvrdet!!
                            m_frequencies.push_back(t_audioModule.AnalyseSoundSpectrum(m_repeatableFrequencyAnalyserChannelID));
                        }
                        else
                        {
                            // do nothing
                        }
                    }
                    break;
                case Doremi::Core::AudioHandler::HOLDREPEATABLEANALYSIS:
                    recordPointer = t_audioModule.GetRecordPointer();
                    // kollar s att vi har spelat in en bit innan vi startar analysen. Om man startar analysen Dirr buggar det ut. TODOLH Definea
                    // 9600 kanske?
                    if(recordPointer > 9600)
                    {
                        m_SoundState = ANALYSEREPEATABLE;
                        m_frequencies.clear();
                        t_audioModule.PlayASound(m_repeatableFrequencyAnalyserSoundID, false, m_repeatableFrequencyAnalyserChannelID);
                        t_audioModule.SetVolumeOnChannel(m_repeatableFrequencyAnalyserChannelID, 0.0f);
                        t_audioModule.SetPriority(m_repeatableFrequencyAnalyserChannelID, 1);
                    }
                    break;
                default:
                    break;
            }

            InputHandlerClient* inputHandler = (InputHandlerClient*)PlayerHandler::GetInstance()->GetDefaultInputHandler();
            if(inputHandler != nullptr)
            {

                if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency0))
                {
                    m_currentFrequency = 0;
                }
                else if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency500))
                {
                    m_currentFrequency = 500;
                }
                else if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency1000))
                {
                    m_currentFrequency = 1000;
                }
            }
            // Send frequence to buffer
            FrequencyBufferHandler* freqBufferHandler = PlayerHandler::GetInstance()->GetDefaultFrequencyBufferHandler();
            if(freqBufferHandler != nullptr)
            {
                freqBufferHandler->BufferFrequency(m_currentFrequency);
                using namespace Doremi::Utilities::Logging;
                m_logger->DebugLog(LogTag::AUDIO, LogLevel::MASS_DATA_PRINT, "F, %f", m_currentFrequency);
            }

            TIME_FUNCTION_STOP
        }

        void AudioHandler::OnEvent(Event* p_event)
        {
            if(p_event->eventType == EventType::ChangeMenuState)
            {
                ChangeMenuState* t_stateEvent = static_cast<ChangeMenuState*>(p_event);

                if(t_stateEvent->state == DoremiStates::RUNGAME)
                {
                    if(m_backgroundSounds.count(BackgroundSound::InGameMainTheme) != 0)
                    {
                        DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
                        t_audioModule.PlayASound(m_backgroundSounds[BackgroundSound::InGameMainTheme], true, m_backgroundChannelId);
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// Project specific
#include <Editor.hpp>

// Third party

// Standard libraries
#ifdef _WIN32
#include <windows.h>
#include <DbgHelp.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#else
#error Platform not supported
#endif
#include <exception>
#include <iostream>
#include <exception> // std::set_unexpected

// The method called when shutting down
void attemptGracefulShutdown();

// Methods set as unexpected and terminate functions
void g_unexpected();
void g_terminate();

// Prints the current stack
void printStack();

// Start the important singletons
void startup();

// Shutdown the important singletons
void shutdown();

// Controlhandler
BOOL CtrlHandler(DWORD fdwCtrlType);

void localMain()
{
    try
    {
        DoremiEditor::EditorMain editor;
        editor.Start();
    }
    catch(const std::exception& e)
    {
        // TODORT log
        std::cout << "Unhandled exception: " << e.what() << std::endl;
        attemptGracefulShutdown();
        exit(1);
    }
    catch(...)
    {
        // TODORT log
        std::cout << "Unhandled unknown exception" << std::endl;
        attemptGracefulShutdown();
        exit(1);
    }
}

#ifdef _WIN32
int main(int argc, const char* argv[])
#else
#error Platform not supported
#endif
{
    std::set_terminate(g_terminate);
    std::set_unexpected(g_unexpected);
    SetErrorMode(SEM_FAILCRITICALERRORS);
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);

    // Run startup code
    startup();

    // TODORT
    // This row is required later as it disables the standard output terminal, we do now want that.
    // However, as people are currently using cout for debugging we'll need this for the moment.
    // FreeConsole();

    __try
    {
        localMain();
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        attemptGracefulShutdown();
        exit(1);
    }

    // Run shutdown code
    shutdown();
    return 0;
}

void g_unexpected() { attemptGracefulShutdown(); }
void g_terminate() { attemptGracefulShutdown(); }

void startup()
{
    // TODORT
    // TODOLOG
    // using namespace Utility::Timer;
    // using namespace Utility::DebugLog;
    // ConsoleManager::Startup();
    // MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Start();
}

void shutdown()
{
    // TODORT
    // TODOLOG
    // using namespace Utility::Timer;
    // using namespace Utility::DebugLog;
    // MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Stop();
    // MeasureTimer::GetInstance().DumpData("client_timings");
    // ConsoleManager::Shutdown();
}

void attemptGracefulShutdown()
{
    // printStack();
    shutdown();
#ifdef _DEBUG
    std::cin.get();
#endif
}

#ifdef _WIN32
// void printStack()
//{
//    unsigned int i;
//    void* stack[100];
//    unsigned short frames;
//    SYMBOL_INFO* symbol;
//    HANDLE process;
//
//    process = GetCurrentProcess();
//
//    SymInitialize(process, NULL, TRUE);
//
//    frames = CaptureStackBackTrace(0, 100, stack, NULL);
//    symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1);
//    symbol->MaxNameLen = 255;
//    symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
//    // TODORT
//    // TODOLOG
//    // using namespace Utility::DebugLog;
//    // VirtualConsole& console = ConsoleManager::GetInstance().CreateNewConsole("stackPrint", false);
//    for (i = 0; i < frames; i++)
//    {
//        SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol);
//        // TODORT
//        // TODOLOG
//        // console.LogText(LogTag::NOTAG, LogLevel::MASS_DATA_PRINT, "%i: %s - 0x%0X\n", frames - i - 1, symbol->Name, symbol->Address);
//    }
//
//    free(symbol);
//}

BOOL CtrlHandler(DWORD fdwCtrlType)
{
    switch(fdwCtrlType)
    {
        // Handle the CTRL-C signal.
        case CTRL_C_EVENT:
            attemptGracefulShutdown();
            return (TRUE);

        // CTRL-CLOSE: confirm that the user wants to exit.
        case CTRL_CLOSE_EVENT:
            attemptGracefulShutdown();
            return (TRUE);

        default:
            return FALSE;
    }
}

#endif<commit_msg>Removed link to dbghelper for Editor<commit_after>// Project specific
#include <Editor.hpp>

// Third party

// Standard libraries
#ifdef _WIN32
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#else
#error Platform not supported
#endif
#include <exception>
#include <iostream>
#include <exception> // std::set_unexpected

// The method called when shutting down
void attemptGracefulShutdown();

// Methods set as unexpected and terminate functions
void g_unexpected();
void g_terminate();

// Start the important singletons
void startup();

// Shutdown the important singletons
void shutdown();

// Controlhandler
BOOL CtrlHandler(DWORD fdwCtrlType);

void localMain()
{
    try
    {
        DoremiEditor::EditorMain editor;
        editor.Start();
    }
    catch(const std::exception& e)
    {
        // TODORT log
        std::cout << "Unhandled exception: " << e.what() << std::endl;
        attemptGracefulShutdown();
        exit(1);
    }
    catch(...)
    {
        // TODORT log
        std::cout << "Unhandled unknown exception" << std::endl;
        attemptGracefulShutdown();
        exit(1);
    }
}

#ifdef _WIN32
int main(int argc, const char* argv[])
#else
#error Platform not supported
#endif
{
    std::set_terminate(g_terminate);
    std::set_unexpected(g_unexpected);
    SetErrorMode(SEM_FAILCRITICALERRORS);
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);

    // Run startup code
    startup();

    // TODORT
    // This row is required later as it disables the standard output terminal, we do now want that.
    // However, as people are currently using cout for debugging we'll need this for the moment.
    // FreeConsole();

    __try
    {
        localMain();
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        attemptGracefulShutdown();
        exit(1);
    }

    // Run shutdown code
    shutdown();
    return 0;
}

void g_unexpected() { attemptGracefulShutdown(); }
void g_terminate() { attemptGracefulShutdown(); }

void startup()
{
    // TODORT
    // TODOLOG
    // using namespace Utility::Timer;
    // using namespace Utility::DebugLog;
    // ConsoleManager::Startup();
    // MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Start();
}

void shutdown()
{
    // TODORT
    // TODOLOG
    // using namespace Utility::Timer;
    // using namespace Utility::DebugLog;
    // MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Stop();
    // MeasureTimer::GetInstance().DumpData("client_timings");
    // ConsoleManager::Shutdown();
}

void attemptGracefulShutdown()
{
    shutdown();
#ifdef _DEBUG
    std::cin.get();
#endif
}

#ifdef _WIN32
BOOL CtrlHandler(DWORD fdwCtrlType)
{
    switch(fdwCtrlType)
    {
        // Handle the CTRL-C signal.
        case CTRL_C_EVENT:
            attemptGracefulShutdown();
            return (TRUE);

        // CTRL-CLOSE: confirm that the user wants to exit.
        case CTRL_CLOSE_EVENT:
            attemptGracefulShutdown();
            return (TRUE);

        default:
            return FALSE;
    }
}

#endif<|endoftext|>


<commit_before><commit_msg>fix empty w:tblW<commit_after><|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

// File <-> streams adapters
//
// Seastar files are block-based due to the reliance on DMA - you must read
// on sector boundaries.  The adapters in this file provide a byte stream
// interface to files, while retaining the zero-copy characteristics of
// seastar files.

#include "file.hh"
#include "iostream.hh"
#include "shared_ptr.hh"

/// Data structure describing options for opening a file input stream
struct file_input_stream_options {
    size_t buffer_size = 8192;    ///< I/O buffer size
    unsigned read_ahead = 0;      ///< Number of extra read-ahead operations
    ::io_priority_class io_priority_class = default_priority_class();
};

// Create an input_stream for a given file, with the specified options.
// Multiple fibers of execution (continuations) may safely open
// multiple input streams concurrently for the same file.
input_stream<char> make_file_input_stream(
        file file, uint64_t offset, file_input_stream_options = {});

// Create an input_stream for reading starting at a given position of the
// given file. Multiple fibers of execution (continuations) may safely open
// multiple input streams concurrently for the same file.
input_stream<char> make_file_input_stream(
        file file, file_input_stream_options = {});

inline
input_stream<char> make_file_input_stream(
        file file, uint64_t offset, uint64_t buffer_size) {
    file_input_stream_options options;
    options.buffer_size = buffer_size;
    return make_file_input_stream(std::move(file), offset, std::move(options));
}

struct file_output_stream_options {
    unsigned buffer_size = 8192;
    unsigned preallocation_size = 1024*1024; // 1MB
    unsigned write_behind = 1; ///< Number of buffers to write in parallel
    ::io_priority_class io_priority_class = default_priority_class();
};

// Create an output_stream for writing starting at the position zero of a
// newly created file.
// NOTE: flush() should be the last thing to be called on a file output stream.
output_stream<char> make_file_output_stream(
        file file,
        uint64_t buffer_size = 8192);

/// Create an output_stream for writing starting at the position zero of a
/// newly created file.
/// NOTE: flush() should be the last thing to be called on a file output stream.
output_stream<char> make_file_output_stream(
        file file,
        file_output_stream_options options);

<commit_msg>fstream: remove unused interface<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

// File <-> streams adapters
//
// Seastar files are block-based due to the reliance on DMA - you must read
// on sector boundaries.  The adapters in this file provide a byte stream
// interface to files, while retaining the zero-copy characteristics of
// seastar files.

#include "file.hh"
#include "iostream.hh"
#include "shared_ptr.hh"

/// Data structure describing options for opening a file input stream
struct file_input_stream_options {
    size_t buffer_size = 8192;    ///< I/O buffer size
    unsigned read_ahead = 0;      ///< Number of extra read-ahead operations
    ::io_priority_class io_priority_class = default_priority_class();
};

// Create an input_stream for a given file, with the specified options.
// Multiple fibers of execution (continuations) may safely open
// multiple input streams concurrently for the same file.
input_stream<char> make_file_input_stream(
        file file, uint64_t offset, file_input_stream_options = {});

// Create an input_stream for reading starting at a given position of the
// given file. Multiple fibers of execution (continuations) may safely open
// multiple input streams concurrently for the same file.
input_stream<char> make_file_input_stream(
        file file, file_input_stream_options = {});

struct file_output_stream_options {
    unsigned buffer_size = 8192;
    unsigned preallocation_size = 1024*1024; // 1MB
    unsigned write_behind = 1; ///< Number of buffers to write in parallel
    ::io_priority_class io_priority_class = default_priority_class();
};

// Create an output_stream for writing starting at the position zero of a
// newly created file.
// NOTE: flush() should be the last thing to be called on a file output stream.
output_stream<char> make_file_output_stream(
        file file,
        uint64_t buffer_size = 8192);

/// Create an output_stream for writing starting at the position zero of a
/// newly created file.
/// NOTE: flush() should be the last thing to be called on a file output stream.
output_stream<char> make_file_output_stream(
        file file,
        file_output_stream_options options);

<|endoftext|>