<commit_before>/*
* Copyright (C) 2008-2011 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*/

#include "application.h"
#include "settingswizard.h"
#include "sharedtimer.h"
#include "connectioninfo.h"
#include <QMessageBox>
#include <QSettings>
#include <QIcon>
#include <Irc>

QByteArray Application::ApplicationData::encoding;
Settings Application::ApplicationData::settings;

Application::Application(int& argc, char* argv[]) : QApplication(argc, argv)
{
    setApplicationName("Communi");
    setOrganizationName("Communi");
    setApplicationVersion(Irc::version());

    QIcon icon;
    icon.addFile(":/resources/icons/16x16/communi.png");
    icon.addFile(":/resources/icons/26x26/communi.png");
    icon.addFile(":/resources/icons/32x32/communi.png");
    icon.addFile(":/resources/icons/48x48/communi.png");
    icon.addFile(":/resources/icons/64x64/communi.png");
    icon.addFile(":/resources/icons/128x128/communi.png");
    setWindowIcon(icon);

    qRegisterMetaTypeStreamOperators<Settings>("Settings");
    qRegisterMetaTypeStreamOperators<ConnectionInfo>("ConnectionInfo");
    qRegisterMetaTypeStreamOperators<ConnectionInfos>("ConnectionInfos");

    QSettings settings;
    ApplicationData::settings = settings.value("settings").value<Settings>();

    SharedTimer::instance()->setInterval(500);
}

Application::~Application()
{
    QSettings settings;
    settings.setValue("settings", ApplicationData::settings);
}

QString Application::applicationSlogan()
{
    return tr("%1 is a simple and light-weight cross-platform IRC client.").arg(applicationName());
}

QByteArray Application::encoding()
{
    return ApplicationData::encoding;
}

void Application::setEncoding(const QByteArray& encoding)
{
    ApplicationData::encoding = encoding;
}

Settings Application::settings()
{
    return ApplicationData::settings;
}

void Application::setSettings(const Settings& settings)
{
    if (ApplicationData::settings != settings)
    {
        ApplicationData::settings = settings;
        QMetaObject::invokeMethod(qApp, "settingsChanged", Q_ARG(Settings, settings));
    }
}

void Application::aboutApplication()
{
    QMessageBox::about(
#ifdef Q_WS_MAC
        0,
#else
        activeWindow(),
#endif // Q_WS_MAC
        applicationName(), QString(
        "
%1
"
        "
%2
"
        "
%3
"
        "
Copyright (C) 2008-2011 J-P Nurmi <"
        "jpnurmi@gmail.com>
")
            .arg(tr("About %1").arg(applicationName()))
            .arg(applicationSlogan())
            .arg(organizationDomain())
        );
}

void Application::aboutOxygen()
{
    QMessageBox::about(
#ifdef Q_WS_MAC
        0,
#else
        activeWindow(),
#endif // Q_WS_MAC
        "Oxygen", QString(
        "
%1
"
        "
http://www.oxygen-icons.org/
"
        ).arg(tr("About %1").arg("Oxygen")));
}

void Application::showSettings()
{
    SettingsWizard wizard(activeWindow());
    wizard.setSettings(settings());
    if (wizard.exec())
        setSettings(wizard.settings());
}
<commit_msg>desktop ex: initialize proper encoding to avoid warnings<commit_after>/*
* Copyright (C) 2008-2011 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*/

#include "application.h"
#include "settingswizard.h"
#include "sharedtimer.h"
#include "connectioninfo.h"
#include <QMessageBox>
#include <QSettings>
#include <QIcon>
#include <Irc>

QByteArray Application::ApplicationData::encoding("UTF-8");
Settings Application::ApplicationData::settings;

Application::Application(int& argc, char* argv[]) : QApplication(argc, argv)
{
    setApplicationName("Communi");
    setOrganizationName("Communi");
    setApplicationVersion(Irc::version());

    QIcon icon;
    icon.addFile(":/resources/icons/16x16/communi.png");
    icon.addFile(":/resources/icons/26x26/communi.png");
    icon.addFile(":/resources/icons/32x32/communi.png");
    icon.addFile(":/resources/icons/48x48/communi.png");
    icon.addFile(":/resources/icons/64x64/communi.png");
    icon.addFile(":/resources/icons/128x128/communi.png");
    setWindowIcon(icon);

    qRegisterMetaTypeStreamOperators<Settings>("Settings");
    qRegisterMetaTypeStreamOperators<ConnectionInfo>("ConnectionInfo");
    qRegisterMetaTypeStreamOperators<ConnectionInfos>("ConnectionInfos");

    QSettings settings;
    ApplicationData::settings = settings.value("settings").value<Settings>();

    SharedTimer::instance()->setInterval(500);
}

Application::~Application()
{
    QSettings settings;
    settings.setValue("settings", ApplicationData::settings);
}

QString Application::applicationSlogan()
{
    return tr("%1 is a simple and light-weight cross-platform IRC client.").arg(applicationName());
}

QByteArray Application::encoding()
{
    return ApplicationData::encoding;
}

void Application::setEncoding(const QByteArray& encoding)
{
    ApplicationData::encoding = encoding;
}

Settings Application::settings()
{
    return ApplicationData::settings;
}

void Application::setSettings(const Settings& settings)
{
    if (ApplicationData::settings != settings)
    {
        ApplicationData::settings = settings;
        QMetaObject::invokeMethod(qApp, "settingsChanged", Q_ARG(Settings, settings));
    }
}

void Application::aboutApplication()
{
    QMessageBox::about(
#ifdef Q_WS_MAC
        0,
#else
        activeWindow(),
#endif // Q_WS_MAC
        applicationName(), QString(
        "
%1
"
        "
%2
"
        "
%3
"
        "
Copyright (C) 2008-2011 J-P Nurmi <"
        "jpnurmi@gmail.com>
")
            .arg(tr("About %1").arg(applicationName()))
            .arg(applicationSlogan())
            .arg(organizationDomain())
        );
}

void Application::aboutOxygen()
{
    QMessageBox::about(
#ifdef Q_WS_MAC
        0,
#else
        activeWindow(),
#endif // Q_WS_MAC
        "Oxygen", QString(
        "
%1
"
        "
http://www.oxygen-icons.org/
"
        ).arg(tr("About %1").arg("Oxygen")));
}

void Application::showSettings()
{
    SettingsWizard wizard(activeWindow());
    wizard.setSettings(settings());
    if (wizard.exec())
        setSettings(wizard.settings());
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2019-2020 the rbfx 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 "../Precompiled.h"

#include "../Graphics/LightmapManager.h"

#include "../Core/Context.h"
#include "../Core/CoreEvents.h"
#include "../Graphics/GlobalIllumination.h"
#include "../Graphics/Octree.h"
#include "../Graphics/Renderer.h"
#include "../Graphics/Zone.h"
#include "../Scene/Scene.h"

#if URHO3D_GLOW
#include "../Glow/IncrementalLightBaker.h"
#endif

namespace Urho3D
{

extern const char* SUBSYSTEM_CATEGORY;

LightmapManager::LightmapManager(Context* context) :
    Component(context)
{
    SubscribeToEvent(E_UPDATE, [this](StringHash eventType, VariantMap& eventData)
    {
        if (bakingScheduled_)
        {
            bakingScheduled_ = false;
            Bake();
        }
    });
}

LightmapManager::~LightmapManager() = default;

void LightmapManager::RegisterObject(Context* context)
{
    static const LightBakingSettings defaultSettings;
    context->RegisterFactory<LightmapManager>(SUBSYSTEM_CATEGORY);

    auto getBake = [](const ClassName& self, Urho3D::Variant& value) { value = false; };
    auto setBake = [](ClassName& self, const Urho3D::Variant& value) { if (value.GetBool()) self.bakingScheduled_ = true; };
    URHO3D_CUSTOM_ACCESSOR_ATTRIBUTE("Bake!", getBake, setBake, bool, false, AM_EDIT);

    URHO3D_ATTRIBUTE("Output Directory", ea::string, settings_.incremental_.outputDirectory_, "", AM_DEFAULT);
    URHO3D_ATTRIBUTE("Lightmap Size", unsigned, settings_.charting_.lightmapSize_, defaultSettings.charting_.lightmapSize_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Texel Density", float, settings_.charting_.texelDensity_, defaultSettings.charting_.texelDensity_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Indirect Multiplier", float, settings_.properties_.indirectMultiplier_, defaultSettings.properties_.indirectMultiplier_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Background Brightness", float, settings_.properties_.backgroundBrightness_, defaultSettings.properties_.backgroundBrightness_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Direct Samples (Lightmap)", unsigned, settings_.directChartTracing_.maxSamples_, defaultSettings.directChartTracing_.maxSamples_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Direct Samples (Light Probes)", unsigned, settings_.directProbesTracing_.maxSamples_, defaultSettings.directProbesTracing_.maxSamples_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Indirect Bounces", unsigned, settings_.indirectChartTracing_.maxBounces_, defaultSettings.indirectChartTracing_.maxBounces_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Indirect Samples (Texture)", unsigned, settings_.indirectChartTracing_.maxSamples_, defaultSettings.indirectChartTracing_.maxSamples_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Indirect Samples (Light Probes)", unsigned, settings_.indirectProbesTracing_.maxSamples_, defaultSettings.indirectProbesTracing_.maxSamples_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Filter Radius (Direct)", unsigned, settings_.directFilter_.kernelRadius_, defaultSettings.directFilter_.kernelRadius_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Filter Radius (Indirect)", unsigned, settings_.indirectFilter_.kernelRadius_, defaultSettings.indirectFilter_.kernelRadius_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Chunk Size", Vector3, settings_.incremental_.chunkSize_, defaultSettings.incremental_.chunkSize_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Chunk Indirect Padding", float, settings_.incremental_.indirectPadding_, defaultSettings.incremental_.indirectPadding_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Chunk Shadow Distance", float, settings_.incremental_.directionalLightShadowDistance_, defaultSettings.incremental_.directionalLightShadowDistance_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Stitch Iterations", unsigned, settings_.stitching_.numIterations_, defaultSettings.stitching_.numIterations_, AM_DEFAULT);
}

void LightmapManager::Bake()
{
    // Fill settings
    settings_.indirectProbesTracing_.maxBounces_ = settings_.indirectChartTracing_.maxBounces_;

    const unsigned numTasks = settings_.charting_.lightmapSize_;
    settings_.geometryBufferPreprocessing_.numTasks_ = numTasks;
    settings_.emissionTracing_.numTasks_ = numTasks;
    settings_.directChartTracing_.numTasks_ = numTasks;
    settings_.directProbesTracing_.numTasks_ = numTasks;
    settings_.indirectChartTracing_.numTasks_ = numTasks;
    settings_.indirectProbesTracing_.numTasks_ = numTasks;

    auto octree = GetScene()->GetComponent<Octree>();
    Zone* zone = octree->GetZone();
    settings_.properties_.backgroundColor_ = zone->GetFogColor().ToVector3();

    // Bake lightmaps if possible
#if URHO3D_GLOW
    DefaultBakedSceneCollector sceneCollector;
    BakedLightMemoryCache lightmapCache;
    IncrementalLightBaker lightBaker;

    if (lightBaker.Initialize(settings_, GetScene(), &sceneCollector, &lightmapCache))
    {
        lightBaker.ProcessScene();
        lightBaker.Bake();
        lightBaker.CommitScene();
    }
#endif

    // Compile light probes
    if (auto gi = GetScene()->GetComponent<GlobalIllumination>())
    {
        gi->CompileLightProbes();
    }
}

}
<commit_msg>Add more logging in LightmapManager.<commit_after>//
// Copyright (c) 2019-2020 the rbfx 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 "../Precompiled.h"

#include "../Graphics/LightmapManager.h"

#include "../Core/Context.h"
#include "../Core/CoreEvents.h"
#include "../Core/Timer.h"
#include "../Graphics/GlobalIllumination.h"
#include "../Graphics/Octree.h"
#include "../Graphics/Renderer.h"
#include "../Graphics/Zone.h"
#include "../IO/Log.h"
#include "../Scene/Scene.h"

#if URHO3D_GLOW
#include "../Glow/IncrementalLightBaker.h"
#endif

namespace Urho3D
{

extern const char* SUBSYSTEM_CATEGORY;

LightmapManager::LightmapManager(Context* context) :
    Component(context)
{
    SubscribeToEvent(E_UPDATE, [this](StringHash eventType, VariantMap& eventData)
    {
        if (bakingScheduled_)
        {
            bakingScheduled_ = false;
            Bake();
        }
    });
}

LightmapManager::~LightmapManager() = default;

void LightmapManager::RegisterObject(Context* context)
{
    static const LightBakingSettings defaultSettings;
    context->RegisterFactory<LightmapManager>(SUBSYSTEM_CATEGORY);

    auto getBake = [](const ClassName& self, Urho3D::Variant& value) { value = false; };
    auto setBake = [](ClassName& self, const Urho3D::Variant& value) { if (value.GetBool()) self.bakingScheduled_ = true; };
    URHO3D_CUSTOM_ACCESSOR_ATTRIBUTE("Bake!", getBake, setBake, bool, false, AM_EDIT);

    URHO3D_ATTRIBUTE("Output Directory", ea::string, settings_.incremental_.outputDirectory_, "", AM_DEFAULT);
    URHO3D_ATTRIBUTE("Lightmap Size", unsigned, settings_.charting_.lightmapSize_, defaultSettings.charting_.lightmapSize_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Texel Density", float, settings_.charting_.texelDensity_, defaultSettings.charting_.texelDensity_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Indirect Multiplier", float, settings_.properties_.indirectMultiplier_, defaultSettings.properties_.indirectMultiplier_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Background Brightness", float, settings_.properties_.backgroundBrightness_, defaultSettings.properties_.backgroundBrightness_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Direct Samples (Lightmap)", unsigned, settings_.directChartTracing_.maxSamples_, defaultSettings.directChartTracing_.maxSamples_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Direct Samples (Light Probes)", unsigned, settings_.directProbesTracing_.maxSamples_, defaultSettings.directProbesTracing_.maxSamples_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Indirect Bounces", unsigned, settings_.indirectChartTracing_.maxBounces_, defaultSettings.indirectChartTracing_.maxBounces_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Indirect Samples (Texture)", unsigned, settings_.indirectChartTracing_.maxSamples_, defaultSettings.indirectChartTracing_.maxSamples_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Indirect Samples (Light Probes)", unsigned, settings_.indirectProbesTracing_.maxSamples_, defaultSettings.indirectProbesTracing_.maxSamples_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Filter Radius (Direct)", unsigned, settings_.directFilter_.kernelRadius_, defaultSettings.directFilter_.kernelRadius_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Filter Radius (Indirect)", unsigned, settings_.indirectFilter_.kernelRadius_, defaultSettings.indirectFilter_.kernelRadius_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Chunk Size", Vector3, settings_.incremental_.chunkSize_, defaultSettings.incremental_.chunkSize_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Chunk Indirect Padding", float, settings_.incremental_.indirectPadding_, defaultSettings.incremental_.indirectPadding_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Chunk Shadow Distance", float, settings_.incremental_.directionalLightShadowDistance_, defaultSettings.incremental_.directionalLightShadowDistance_, AM_DEFAULT);
    URHO3D_ATTRIBUTE("Stitch Iterations", unsigned, settings_.stitching_.numIterations_, defaultSettings.stitching_.numIterations_, AM_DEFAULT);
}

void LightmapManager::Bake()
{
    // Fill settings
    settings_.indirectProbesTracing_.maxBounces_ = settings_.indirectChartTracing_.maxBounces_;

    const unsigned numTasks = settings_.charting_.lightmapSize_;
    settings_.geometryBufferPreprocessing_.numTasks_ = numTasks;
    settings_.emissionTracing_.numTasks_ = numTasks;
    settings_.directChartTracing_.numTasks_ = numTasks;
    settings_.directProbesTracing_.numTasks_ = numTasks;
    settings_.indirectChartTracing_.numTasks_ = numTasks;
    settings_.indirectProbesTracing_.numTasks_ = numTasks;

    auto octree = GetScene()->GetComponent<Octree>();
    Zone* zone = octree->GetZone();
    settings_.properties_.backgroundColor_ = zone->GetFogColor().ToVector3();

    // Bake light if possible
#if URHO3D_GLOW
    Timer timer;
    DefaultBakedSceneCollector sceneCollector;
    BakedLightMemoryCache lightmapCache;
    IncrementalLightBaker lightBaker;

    if (lightBaker.Initialize(settings_, GetScene(), &sceneCollector, &lightmapCache))
    {
        lightBaker.ProcessScene();
        lightBaker.Bake();
        lightBaker.CommitScene();
    }
#else
    URHO3D_LOGERROR("Enable URHO3D_GLOW in build options");
#endif

    // Compile light probes
    if (auto gi = GetScene()->GetComponent<GlobalIllumination>())
    {
        gi->CompileLightProbes();
    }

#if URHO3D_GLOW
    // Log overall time
    const unsigned totalMSec = timer.GetMSec(true);
    URHO3D_LOGINFO("Light baking is finished in {} seconds", totalMSec / 1000);
#endif
}

}
<|endoftext|>


<commit_before>
#include "MarchingCubesShaded.h"
#include "MappedData.h"
#include "ShaderProgram.h"
#include "MarchingCubesFactory.h"
#include "Camera.h"
#include <glm\geometric.hpp>
#include <glm\common.hpp>
#include <glm\gtc\matrix_transform.hpp>
#include <glm\gtc\type_ptr.hpp>

using namespace std;

MarchingCubesShaded::MarchingCubesShaded( const char* filePath )
{
	MappedData paramFile( filePath );

	vPosition = paramFile.getData("base","position").getVec3f();
	vSpan = paramFile.getData("base","span").getVec3f();

	dataWidth = paramFile.getData("base","dataWidth").getInt();
	dataHeight = paramFile.getData("base","dataHeight").getInt();
	dataDepth = paramFile.getData("base","dataDepth").getInt();
	dataWidth = dataWidth<DATA_MIN ? DATA_MIN : dataWidth;
	dataHeight = dataHeight<DATA_MIN ? DATA_MIN : dataHeight;
	dataDepth = dataDepth<DATA_MIN ? DATA_MIN : dataDepth;

	dataMax = paramFile.getData("base","maxValue").getInt();
	treshold = paramFile.getData("base","treshold").getFloat( 0.5f );

	string vertex = paramFile.getData("shaders", "v").getStringData();
	string geometry = paramFile.getData("shaders", "g").getStringData();
	string fragment = paramFile.getData("shaders", "f").getStringData();

	mcShader = ShaderProgram::CreateShader( vertex, geometry, fragment );

	GLuint programHandle = mcShader->getProgramID();

	initDataField( );

	initGridBuffer( );

	mcShader->turnOn();
		mcShader->setUniformI( "Data", 0 );
		mcShader->setUniformI( "TriTable", 1 );

		mcShader->setUniformV3( "VerticeOffsets[0]", 0.0f,			0.0f,		0.0f		);
		mcShader->setUniformV3( "VerticeOffsets[1]", gridStep.x,	0.0f,		0.0f		);
		mcShader->setUniformV3( "VerticeOffsets[2]", gridStep.x,	gridStep.y, 0.0f		);
		mcShader->setUniformV3( "VerticeOffsets[3]", 0.0f,			gridStep.y, 0.0f		);
		mcShader->setUniformV3( "VerticeOffsets[4]", 0.0f,			0.0f,		gridStep.z	);
		mcShader->setUniformV3( "VerticeOffsets[5]", gridStep.x,	0.0f,		gridStep.z	);
		mcShader->setUniformV3( "VerticeOffsets[6]", gridStep.x,	gridStep.y, gridStep.z	);
		mcShader->setUniformV3( "VerticeOffsets[7]", 0.0f,			gridStep.y, gridStep.z	);

		mcShader->setUniformV3( "DataStep", 1.0f/dataWidth, 1.0f/dataHeight, 1.0f/dataDepth );
	mcShader->turnOff();

	clear();
}

MarchingCubesShaded::~MarchingCubesShaded( )
{
	delete [] dataField;
	// delete buffer and vao
	glDeleteBuffers(1,&gridHandle);
	glDeleteVertexArrays(1,&gridVao);
}

// Create a 3D grid of points in the span od 0,0,0 - 1,1,1
// This will be bound to the VAO and sent to the shader as vertices
// Actual data that generates the marching cube mesh is sent as a 3D texture
void MarchingCubesShaded::initGridBuffer( )
{
	gridStep = vec3f(1,1,1) / (vec3f(dataWidth, dataHeight, dataDepth)-vec3f(1,1,1));
	gridElementCount = (dataWidth + 1)*(dataHeight + 1)*(dataDepth + 1);

	int gridTotalSize =  gridElementCount*3;
	float* grid = new float[gridTotalSize];
	int index = 0;
	for( float x = -gridStep.x; x <= 1.0f; x+=gridStep.x )
	{
		for( float y = -gridStep.y; y <= 1.0f; y+=gridStep.y )
		{
			for( float z = -gridStep.z; z <= 1.0f; z+=gridStep.z )
			{
				grid[ index   ] = x;
				grid[ index+1 ] = y;
				grid[ index+2 ] = z;
				index += 3;
			}
		}
	}

	glGenBuffers(1, &gridHandle);
	glBindBuffer( GL_ARRAY_BUFFER, gridHandle );
	glBufferData( GL_ARRAY_BUFFER, gridTotalSize * sizeof(float), grid, GL_STATIC_DRAW );
	delete[] grid;

	glGenVertexArrays( 1, &gridVao );
	glBindVertexArray( gridVao );
	glEnableVertexAttribArray(0);
	glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL );

	glBindVertexArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glDisableVertexAttribArray(0);
}

void MarchingCubesShaded::initDataField( )
{
	// MC DATA
	glGenTextures(1, &dataTexID);

	glActiveTexture(GL_TEXTURE0);
	glEnable(GL_TEXTURE_3D);
	glBindTexture(GL_TEXTURE_3D, dataTexID);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
	glDisable(GL_TEXTURE_3D);

	dataSize = dataWidth * dataHeight * dataDepth;
	deltaSpan = vSpan / vec3f( dataWidth, dataHeight, dataDepth );
	dataField = new float[ dataSize ]();
	dataChanged = true;
//	glTexImage3D( GL_TEXTURE_3D, 0, GL_ALPHA32F_ARB, dataWidth, dataHeight, dataDepth, 0, GL_ALPHA, GL_FLOAT, dataField);

}

void MarchingCubesShaded::setUnchecked( int x, int y, int z, float value )
{
	float &data = dataField[ x*dataHeight*dataDepth + y*dataDepth + z ];
	data = contain(value+data, 0.0f, dataMax);
	dataChanged = true;
}

void MarchingCubesShaded::set( int x, int y, int z, float value )
{
	if( x<1 || y<1  || z<1 || x>=dataWidth-1 || y>=dataHeight-1 || z>=dataDepth-1 ) return;
	float &data = dataField[ x*dataHeight*dataDepth + y*dataDepth + z ];
	data = contain(value+data, 0.0f, dataMax);
	dataChanged = true;
}

void MarchingCubesShaded::set( int position, float value )
{
	if( position<0 || position>dataSize ) return;
	dataField[ position ] = contain(value, 0.0f, dataMax);
	dataChanged = true;
}

void MarchingCubesShaded::clear()
{
	memset( dataField, 0, dataSize*sizeof(float) );
	dataChanged = true;
}

vec3f MarchingCubesShaded::getScale()
{
	return vSpan;
}

vec3f MarchingCubesShaded::getPosition()
{
	return vPosition;
}

float MarchingCubesShaded::getTreshold()
{
	return this->treshold;
}

void MarchingCubesShaded::setTreshold( float t )
{
	this->treshold = t;
}

void MarchingCubesShaded::putSphere( float x, float y, float z, float r )
{
	float value;
	vec3f start = vec3f( x-r, y-r, z-r );
	glm::clamp( start, vPosition, vPosition+vSpan );
	start -= vPosition;
	start /= deltaSpan;

	vec3f end = vec3f( x+r, y+r, z+r );
	glm::clamp( end, vPosition, vPosition+vSpan );
	end -= vPosition;
	end /= deltaSpan;

	vec3f center = (vec3f( x,y,z ) - vPosition) / deltaSpan;
	r /= glm::length( deltaSpan );

	for(int i=start.x; i<end.x; i++)
	{
		for(int j=start.y; j<end.y; j++)
		{
			for(int k=start.z; k<end.z; k++)
			{
				value = r-glm::length(center-vec3f(i,j,k))+1;
				if (value > 0)
				{
					set(i, j, k, value);
				}
			}
		}
	}
}

void MarchingCubesShaded::draw(const Camera& camera)
{
	glm::mat4 mvp = camera.getViewProjection() * transform.getTransformMatrix();
	glm::vec3 eye = camera.getPosition();

	glDisable( GL_CULL_FACE );
	mcShader->turnOn();
		mcShader->setUniformF( "Treshold", this->treshold );
		mcShader->setUniformV3( "Color", 0.0f, 0.3f, 1.0f );
		mcShader->setUniformV3( "Diffuse", 0.4f, 0.9f, 0.0f );
		mcShader->setUniformV3( "Specular", 1.0f, 1.0f, 1.0f );
		mcShader->setUniformV3( "Ambient", 0.3f, 0.8f, 0.6f );
		mcShader->setUniformV3( "LightPosition", 20.f, -15.0f, 5.0f );
		mcShader->setUniformV3( "Eye", eye.x, eye.y, eye.z );
		mcShader->setUniformM4( "MVP", glm::value_ptr(mvp) );

		MarchingCubesFactory::setTexture( GL_TEXTURE1 );

		glEnable( GL_TEXTURE_3D );
		glActiveTexture( GL_TEXTURE0 );
		glBindTexture( GL_TEXTURE_3D, dataTexID );
		if (dataChanged)
		{
			glTexImage3D(GL_TEXTURE_3D, 0, GL_ALPHA32F_ARB, dataWidth, dataHeight, dataDepth, 0, GL_ALPHA, GL_FLOAT, dataField);
		}

		// !
		GLboolean blendEnabled = glIsEnabled( GL_BLEND );
		glEnable( GL_BLEND );
		glBlendFunc(GL_ONE, GL_ONE);
		glDepthMask(GL_FALSE);
			glBindVertexArray(gridVao);
			glDrawArrays(GL_POINTS, 0, gridElementCount );
			glBindVertexArray(0);
		glDepthMask(GL_TRUE);
		if( !blendEnabled ) glDisable( GL_BLEND );

		glDisable( GL_TEXTURE_3D);
	mcShader->turnOff();
	glEnable( GL_CULL_FACE );
}<commit_msg>MCS: forgot to reset the changed flag. Moved setting of fixed uniforms.<commit_after>
#include "MarchingCubesShaded.h"
#include "MappedData.h"
#include "ShaderProgram.h"
#include "MarchingCubesFactory.h"
#include "Camera.h"
#include <glm\geometric.hpp>
#include <glm\common.hpp>
#include <glm\gtc\matrix_transform.hpp>
#include <glm\gtc\type_ptr.hpp>

using namespace std;

MarchingCubesShaded::MarchingCubesShaded( const char* filePath )
{
	MappedData paramFile( filePath );

	vPosition = paramFile.getData("base","position").getVec3f();
	vSpan = paramFile.getData("base","span").getVec3f();

	dataWidth = paramFile.getData("base","dataWidth").getInt();
	dataHeight = paramFile.getData("base","dataHeight").getInt();
	dataDepth = paramFile.getData("base","dataDepth").getInt();
	dataWidth = dataWidth<DATA_MIN ? DATA_MIN : dataWidth;
	dataHeight = dataHeight<DATA_MIN ? DATA_MIN : dataHeight;
	dataDepth = dataDepth<DATA_MIN ? DATA_MIN : dataDepth;

	dataMax = paramFile.getData("base","maxValue").getInt();
	treshold = paramFile.getData("base","treshold").getFloat( 0.5f );

	string vertex = paramFile.getData("shaders", "v").getStringData();
	string geometry = paramFile.getData("shaders", "g").getStringData();
	string fragment = paramFile.getData("shaders", "f").getStringData();

	mcShader = ShaderProgram::CreateShader( vertex, geometry, fragment );

	GLuint programHandle = mcShader->getProgramID();

	initDataField( );

	initGridBuffer( );

	mcShader->turnOn();
		mcShader->setUniformI( "Data", 0 );
		mcShader->setUniformI( "TriTable", 1 );

		mcShader->setUniformV3( "VerticeOffsets[0]", 0.0f,			0.0f,		0.0f		);
		mcShader->setUniformV3( "VerticeOffsets[1]", gridStep.x,	0.0f,		0.0f		);
		mcShader->setUniformV3( "VerticeOffsets[2]", gridStep.x,	gridStep.y, 0.0f		);
		mcShader->setUniformV3( "VerticeOffsets[3]", 0.0f,			gridStep.y, 0.0f		);
		mcShader->setUniformV3( "VerticeOffsets[4]", 0.0f,			0.0f,		gridStep.z	);
		mcShader->setUniformV3( "VerticeOffsets[5]", gridStep.x,	0.0f,		gridStep.z	);
		mcShader->setUniformV3( "VerticeOffsets[6]", gridStep.x,	gridStep.y, gridStep.z	);
		mcShader->setUniformV3( "VerticeOffsets[7]", 0.0f,			gridStep.y, gridStep.z	);

		mcShader->setUniformV3("Color", 0.0f, 0.3f, 1.0f);
		mcShader->setUniformV3("Diffuse", 0.4f, 0.9f, 0.0f);
		mcShader->setUniformV3("Specular", 1.0f, 1.0f, 1.0f);
		mcShader->setUniformV3("Ambient", 0.3f, 0.8f, 0.6f);
		mcShader->setUniformV3("LightPosition", 20.f, -15.0f, 5.0f);

		mcShader->setUniformV3( "DataStep", 1.0f/dataWidth, 1.0f/dataHeight, 1.0f/dataDepth );
	mcShader->turnOff();

	clear();
}

MarchingCubesShaded::~MarchingCubesShaded( )
{
	delete [] dataField;
	// delete buffer and vao
	glDeleteBuffers(1,&gridHandle);
	glDeleteVertexArrays(1,&gridVao);
}

// Create a 3D grid of points in the span od 0,0,0 - 1,1,1
// This will be bound to the VAO and sent to the shader as vertices
// Actual data that generates the marching cube mesh is sent as a 3D texture
void MarchingCubesShaded::initGridBuffer( )
{
	gridStep = vec3f(1,1,1) / (vec3f(dataWidth, dataHeight, dataDepth)-vec3f(1,1,1));
	gridElementCount = (dataWidth + 1)*(dataHeight + 1)*(dataDepth + 1);

	int gridTotalSize =  gridElementCount*3;
	float* grid = new float[gridTotalSize];
	int index = 0;
	for( float x = -gridStep.x; x <= 1.0f; x+=gridStep.x )
	{
		for( float y = -gridStep.y; y <= 1.0f; y+=gridStep.y )
		{
			for( float z = -gridStep.z; z <= 1.0f; z+=gridStep.z )
			{
				grid[ index   ] = x;
				grid[ index+1 ] = y;
				grid[ index+2 ] = z;
				index += 3;
			}
		}
	}

	glGenBuffers(1, &gridHandle);
	glBindBuffer( GL_ARRAY_BUFFER, gridHandle );
	glBufferData( GL_ARRAY_BUFFER, gridTotalSize * sizeof(float), grid, GL_STATIC_DRAW );
	delete[] grid;

	glGenVertexArrays( 1, &gridVao );
	glBindVertexArray( gridVao );
	glEnableVertexAttribArray(0);
	glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL );

	glBindVertexArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glDisableVertexAttribArray(0);
}

void MarchingCubesShaded::initDataField( )
{
	// MC DATA
	glGenTextures(1, &dataTexID);

	glActiveTexture(GL_TEXTURE0);
	glEnable(GL_TEXTURE_3D);
	glBindTexture(GL_TEXTURE_3D, dataTexID);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
	glDisable(GL_TEXTURE_3D);

	dataSize = dataWidth * dataHeight * dataDepth;
	deltaSpan = vSpan / vec3f( dataWidth, dataHeight, dataDepth );
	dataField = new float[ dataSize ]();
	dataChanged = true;
	// data is updated when changed
//	glTexImage3D( GL_TEXTURE_3D, 0, GL_ALPHA32F_ARB, dataWidth, dataHeight, dataDepth, 0, GL_ALPHA, GL_FLOAT, dataField);

}

void MarchingCubesShaded::setUnchecked( int x, int y, int z, float value )
{
	float &data = dataField[ x*dataHeight*dataDepth + y*dataDepth + z ];
	data = contain(value+data, 0.0f, dataMax);
	dataChanged = true;
}

void MarchingCubesShaded::set( int x, int y, int z, float value )
{
	if( x<1 || y<1  || z<1 || x>=dataWidth-1 || y>=dataHeight-1 || z>=dataDepth-1 ) return;
	float &data = dataField[ x*dataHeight*dataDepth + y*dataDepth + z ];
	data = contain(value+data, 0.0f, dataMax);
	dataChanged = true;
}

void MarchingCubesShaded::set( int position, float value )
{
	if( position<0 || position>dataSize ) return;
	dataField[ position ] = contain(value, 0.0f, dataMax);
	dataChanged = true;
}

void MarchingCubesShaded::clear()
{
	memset( dataField, 0, dataSize*sizeof(float) );
	dataChanged = true;
}

vec3f MarchingCubesShaded::getScale()
{
	return vSpan;
}

vec3f MarchingCubesShaded::getPosition()
{
	return vPosition;
}

float MarchingCubesShaded::getTreshold()
{
	return this->treshold;
}

void MarchingCubesShaded::setTreshold( float t )
{
	this->treshold = t;
}

void MarchingCubesShaded::putSphere( float x, float y, float z, float r )
{
	float value;
	vec3f start = vec3f( x-r, y-r, z-r );
	glm::clamp( start, vPosition, vPosition+vSpan );
	start -= vPosition;
	start /= deltaSpan;

	vec3f end = vec3f( x+r, y+r, z+r );
	glm::clamp( end, vPosition, vPosition+vSpan );
	end -= vPosition;
	end /= deltaSpan;

	vec3f center = (vec3f( x,y,z ) - vPosition) / deltaSpan;
	r /= glm::length( deltaSpan );

	for(int i=start.x; i<end.x; i++)
	{
		for(int j=start.y; j<end.y; j++)
		{
			for(int k=start.z; k<end.z; k++)
			{
				value = r-glm::length(center-vec3f(i,j,k))+1;
				if (value > 0)
				{
					set(i, j, k, value);
				}
			}
		}
	}
}

void MarchingCubesShaded::draw(const Camera& camera)
{
	glm::mat4 mvp = camera.getViewProjection() * transform.getTransformMatrix();
	glm::vec3 eye = camera.getPosition();

	glDisable( GL_CULL_FACE );
	mcShader->turnOn();
		mcShader->setUniformF( "Treshold", this->treshold );
		mcShader->setUniformV3( "Eye", eye.x, eye.y, eye.z );
		mcShader->setUniformM4( "MVP", glm::value_ptr(mvp) );

		MarchingCubesFactory::setTexture( GL_TEXTURE1 );

		glEnable( GL_TEXTURE_3D );
		glActiveTexture( GL_TEXTURE0 );
		glBindTexture( GL_TEXTURE_3D, dataTexID );
		if (dataChanged)
		{
			glTexImage3D(GL_TEXTURE_3D, 0, GL_ALPHA32F_ARB, dataWidth, dataHeight, dataDepth, 0, GL_ALPHA, GL_FLOAT, dataField);
			dataChanged = false;
		}

		// !
		GLboolean blendEnabled = glIsEnabled( GL_BLEND );
		glEnable( GL_BLEND );
		glBlendFunc(GL_ONE, GL_ONE);
		glDepthMask(GL_FALSE);
			glBindVertexArray(gridVao);
			glDrawArrays(GL_POINTS, 0, gridElementCount );
			glBindVertexArray(0);
		glDepthMask(GL_TRUE);
		if( !blendEnabled ) glDisable( GL_BLEND );

		glDisable( GL_TEXTURE_3D);
	mcShader->turnOff();
	glEnable( GL_CULL_FACE );
}<|endoftext|>


<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.

#include <osgViewer/Viewer>
#include <osgViewer/StatsHandler>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>

#if USE_QT4

    #include <QtCore/QTimer>
    #include <QtGui/QKeyEvent>
    #include <QtGui/QApplication>
    #include <QtOpenGL/QGLWidget>

    using Qt::WFlags;

#else

    class QWidget;
    #include <qtimer.h>
    #include <qgl.h>
    #include <qapplication.h>

#endif

#include <iostream>

class AdapterWidget : public QGLWidget
{
public:

    AdapterWidget( QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0 );

    virtual ~AdapterWidget() {}

    osgViewer::GraphicsWindow* getGraphicsWindow() { return _gw.get(); }
    const osgViewer::GraphicsWindow* getGraphicsWindow() const { return _gw.get(); }

protected:

    void init();

    virtual void resizeGL( int width, int height );
    virtual void keyPressEvent( QKeyEvent* event );
    virtual void keyReleaseEvent( QKeyEvent* event );
    virtual void mousePressEvent( QMouseEvent* event );
    virtual void mouseReleaseEvent( QMouseEvent* event );
    virtual void mouseMoveEvent( QMouseEvent* event );

    QTimer _timer;

    osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _gw;
};

AdapterWidget::AdapterWidget( QWidget * parent, const char * name, const QGLWidget * shareWidget, WFlags f):
    QGLWidget(parent, name, shareWidget, f)
{
    connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL()));
    _timer.start(10);

    _gw = new osgViewer::GraphicsWindowEmbedded(0,0,width(),height());
}

void AdapterWidget::resizeGL( int width, int height )
{
    _gw->getEventQueue()->windowResize(0, 0, width, height );
    _gw->resized(0,0,width,height);
}

void AdapterWidget::keyPressEvent( QKeyEvent* event )
{
    _gw->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() );
}

void AdapterWidget::keyReleaseEvent( QKeyEvent* event )
{
    _gw->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() );
}

void AdapterWidget::mousePressEvent( QMouseEvent* event )
{
    int button = 0;
    switch(event->button())
    {
        case(Qt::LeftButton): button = 1; break;
        case(Qt::MidButton): button = 2; break;
        case(Qt::RightButton): button = 3; break;
        case(Qt::NoButton): button = 0; break;
        default: button = 0; break;
    }
    _gw->getEventQueue()->mouseButtonPress(event->x(), event->y(), button);
}

void AdapterWidget::mouseReleaseEvent( QMouseEvent* event )
{
    int button = 0;
    switch(event->button())
    {
        case(Qt::LeftButton): button = 1; break;
        case(Qt::MidButton): button = 2; break;
        case(Qt::RightButton): button = 3; break;
        case(Qt::NoButton): button = 0; break;
        default: button = 0; break;
    }
    _gw->getEventQueue()->mouseButtonRelease(event->x(), event->y(), button);
}

void AdapterWidget::mouseMoveEvent( QMouseEvent* event )
{
    _gw->getEventQueue()->mouseMotion(event->x(), event->y());
}

class ViewerQT : public AdapterWidget, public osgViewer::Viewer
{
    public:

        ViewerQT(QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0):
            AdapterWidget( parent, name, shareWidget, f )
        {
            getCamera()->setViewport(new osg::Viewport(0,0,width(),height()));
            getCamera()->setGraphicsContext(getGraphicsWindow());
            setThreadingModel(osgViewer::Viewer::SingleThreaded);
        }

        virtual void initializeGL()
        {
            QGLWidget::initializeGL();
        }

        virtual void paintGL()
        {
            frame();
        }

};

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    if (argc<2)
    {
        std::cout << argv[0] <<": requires filename argument." << std::endl;
        return 1;
    }

    // load the scene.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
    if (!loadedModel)
    {
        std::cout << argv[0] <<": No data loaded." << std::endl;
        return 1;
    }

    ViewerQT* viewerWindow = new ViewerQT;

    viewerWindow->setSceneData(loadedModel.get());
    viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator);
    viewerWindow->addEventHandler(new osgViewer::StatsHandler);

    viewerWindow->show();
    a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );

    return a.exec();
}

/*EOF*/
<commit_msg>Cleaned up example<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.

#include <osgViewer/Viewer>
#include <osgViewer/StatsHandler>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>

#if USE_QT4

    #include <QtCore/QTimer>
    #include <QtGui/QKeyEvent>
    #include <QtGui/QApplication>
    #include <QtOpenGL/QGLWidget>

    using Qt::WFlags;

#else

    class QWidget;
    #include <qtimer.h>
    #include <qgl.h>
    #include <qapplication.h>

#endif

#include <iostream>

class AdapterWidget : public QGLWidget
{
    public:

        AdapterWidget( QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0 );

        virtual ~AdapterWidget() {}

        osgViewer::GraphicsWindow* getGraphicsWindow() { return _gw.get(); }
        const osgViewer::GraphicsWindow* getGraphicsWindow() const { return _gw.get(); }

    protected:

        void init();

        virtual void resizeGL( int width, int height );
        virtual void keyPressEvent( QKeyEvent* event );
        virtual void keyReleaseEvent( QKeyEvent* event );
        virtual void mousePressEvent( QMouseEvent* event );
        virtual void mouseReleaseEvent( QMouseEvent* event );
        virtual void mouseMoveEvent( QMouseEvent* event );

        osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _gw;
};

AdapterWidget::AdapterWidget( QWidget * parent, const char * name, const QGLWidget * shareWidget, WFlags f):
    QGLWidget(parent, name, shareWidget, f)
{
    _gw = new osgViewer::GraphicsWindowEmbedded(0,0,width(),height());
}

void AdapterWidget::resizeGL( int width, int height )
{
    _gw->getEventQueue()->windowResize(0, 0, width, height );
    _gw->resized(0,0,width,height);
}

void AdapterWidget::keyPressEvent( QKeyEvent* event )
{
    _gw->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() );
}

void AdapterWidget::keyReleaseEvent( QKeyEvent* event )
{
    _gw->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() );
}

void AdapterWidget::mousePressEvent( QMouseEvent* event )
{
    int button = 0;
    switch(event->button())
    {
        case(Qt::LeftButton): button = 1; break;
        case(Qt::MidButton): button = 2; break;
        case(Qt::RightButton): button = 3; break;
        case(Qt::NoButton): button = 0; break;
        default: button = 0; break;
    }
    _gw->getEventQueue()->mouseButtonPress(event->x(), event->y(), button);
}

void AdapterWidget::mouseReleaseEvent( QMouseEvent* event )
{
    int button = 0;
    switch(event->button())
    {
        case(Qt::LeftButton): button = 1; break;
        case(Qt::MidButton): button = 2; break;
        case(Qt::RightButton): button = 3; break;
        case(Qt::NoButton): button = 0; break;
        default: button = 0; break;
    }
    _gw->getEventQueue()->mouseButtonRelease(event->x(), event->y(), button);
}

void AdapterWidget::mouseMoveEvent( QMouseEvent* event )
{
    _gw->getEventQueue()->mouseMotion(event->x(), event->y());
}

class ViewerQT : public osgViewer::Viewer, public AdapterWidget
{
    public:

        ViewerQT(QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0):
            AdapterWidget( parent, name, shareWidget, f )
        {
            getCamera()->setViewport(new osg::Viewport(0,0,width(),height()));
            getCamera()->setGraphicsContext(getGraphicsWindow());
            setThreadingModel(osgViewer::Viewer::SingleThreaded);

            connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL()));
            _timer.start(10);
        }

        virtual void paintGL()
        {
            frame();
        }

    protected:

        QTimer _timer;

};

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    if (argc<2)
    {
        std::cout << argv[0] <<": requires filename argument." << std::endl;
        return 1;
    }

    // load the scene.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
    if (!loadedModel)
    {
        std::cout << argv[0] <<": No data loaded." << std::endl;
        return 1;
    }

    ViewerQT* viewerWindow = new ViewerQT;

    viewerWindow->setSceneData(loadedModel.get());
    viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator);
    viewerWindow->addEventHandler(new osgViewer::StatsHandler);

    viewerWindow->show();
    a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );

    return a.exec();
}

/*EOF*/
<|endoftext|>


<commit_before>/**
   Copyright (c) 2014-2015, Sandia Corporation
   All rights reserved.

   This file is part of fast-matmul and is under the BSD 2-Clause License,
   which can be found in the LICENSE file in the root directory, or at
   http://opensource.org/licenses/BSD-2-Clause.
*/

#include "common.hpp"
#ifdef __INTEL_MKL__
# include "mkl.h"
#endif

#include "scaling.hpp"
#include "strassen.hpp"

#include <algorithm>
#include <stdexcept>
#include <vector>

enum Algorithm {
  CLASSICAL = 0,
  STRASSEN,
  STRASSEN_SCALED,
};

// Run a single benchmark for multiplying m x k x n with num_steps of recursion.
// To just call GEMM, set num_steps to zero.
// The median of five trials is printed to std::cout.
// If run_check is true, then it also
void SingleBenchmark(int m, int k, int n, int alg) {
  // Run a set number of trials and pick the median time.
  int num_trials = 5;
  std::vector<double> times(num_trials);
  for (int trial = 0; trial < num_trials; ++trial) {
    Matrix<double> A = RandomMatrix<double>(m, k);
    Matrix<double> B = RandomMatrix<double>(k, n);
    Matrix<double> C(m, n);
    if (alg == CLASSICAL) {
      times[trial] = Time([&] { MatMul(A, B, C); });
    } else if (alg == STRASSEN) {
      times[trial] = Time([&] { strassen::FastMatmul(A, B, C, 1); });
    } else if (alg == STRASSEN_SCALED) {
      times[trial] = Time([&] {
	  Matrix<double> A_roi = A;
	  Matrix<double> B_roi = B;
	  std::vector<double> r_roi, s_roi;
	  Scaling(A_roi, B_roi, 3, r_roi, s_roi, OUTSIDE_INSIDE);
	  strassen::FastMatmul(A, B, C, 1);
	  PostProcessScaling(C, r_roi, s_roi);
	});
    }
  }

  // Spit out the median time
  std::sort(times.begin(), times.end());
  size_t ind = num_trials / 2;
  std::cout << " " << m << " " << k << " " << n << " "
            << " " << times[ind] << "; ";
}

int main(int argc, char **argv) {
  auto opts = GetOpts(argc, argv);

  int start = 1000;
  int end = 7500;
  int skip = 500;

  std::cout << "Classical" << std::endl;
  for (int N = start; N <= end; N += skip) {
    SingleBenchmark(N, N, N, CLASSICAL);
  }
  std::cout << std::endl;

  std::cout << "Strassen" << std::endl;
  for (int N = start; N <= end; N += skip) {
    SingleBenchmark(N, N, N, STRASSEN);
  }
  std::cout << std::endl;

  std::cout << "Strassen" << std::endl;
  for (int N = start; N <= end; N += skip) {
    SingleBenchmark(N, N, N, STRASSEN_SCALED);
  }
  std::cout << std::endl;

  return 0;
}
<commit_msg>Clean up code a little bit<commit_after>/**
   Copyright (c) 2014-2015, Sandia Corporation
   All rights reserved.

   This file is part of fast-matmul and is under the BSD 2-Clause License,
   which can be found in the LICENSE file in the root directory, or at
   http://opensource.org/licenses/BSD-2-Clause.
*/

#include "common.hpp"
#ifdef __INTEL_MKL__
# include "mkl.h"
#endif

#include "scaling.hpp"
#include "strassen.hpp"

#include <algorithm>
#include <stdexcept>
#include <vector>

enum Algorithm {
  CLASSICAL = 0,
  STRASSEN,
  STRASSEN_SCALED,
};

const int kNumScalingSteps = 5;
const int kNumTrials = 5;

// Run a single benchmark for multiplying m x k x n with num_steps of recursion.
// To just call GEMM, set num_steps to zero.
// The median of five trials is printed to std::cout.
// If run_check is true, then it also
void SingleBenchmark(int m, int k, int n, int alg) {
  // Run a set number of trials and pick the median time.
  int num_trials = 5;
  std::vector<double> times(num_trials);
  for (int trial = 0; trial < kNumTrials; ++trial) {
    Matrix<double> A = RandomMatrix<double>(m, k);
    Matrix<double> B = RandomMatrix<double>(k, n);
    Matrix<double> C(m, n);
    if (alg == CLASSICAL) {
      times[trial] = Time([&] { MatMul(A, B, C); });
    } else if (alg == STRASSEN) {
      times[trial] = Time([&] { strassen::FastMatmul(A, B, C, 1); });
    } else if (alg == STRASSEN_SCALED) {
      times[trial] = Time([&] {
	  Matrix<double> A_roi = A;
	  Matrix<double> B_roi = B;
	  std::vector<double> r_roi, s_roi;
	  Scaling(A_roi, B_roi, kNumScalingSteps, r_roi, s_roi, OUTSIDE_INSIDE);
	  strassen::FastMatmul(A, B, C, 1);
	  PostProcessScaling(C, r_roi, s_roi);
	});
    }
  }

  // Spit out the median time
  std::sort(times.begin(), times.end());
  size_t ind = num_trials / 2;
  std::cout << " " << m << " " << k << " " << n << " "
            << " " << times[ind] << "; ";
}

int main(int argc, char **argv) {
  auto opts = GetOpts(argc, argv);

  int start = 1000;
  int end = 7500;
  int skip = 500;

  std::cout << "Classical" << std::endl;
  for (int N = start; N <= end; N += skip) {
    SingleBenchmark(N, N, N, CLASSICAL);
  }
  std::cout << std::endl;

  std::cout << "Strassen" << std::endl;
  for (int N = start; N <= end; N += skip) {
    SingleBenchmark(N, N, N, STRASSEN);
  }
  std::cout << std::endl;

  std::cout << "Strassen" << std::endl;
  for (int N = start; N <= end; N += skip) {
    SingleBenchmark(N, N, N, STRASSEN_SCALED);
  }
  std::cout << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: style.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2008-01-07 08:55:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SFXSTYLE_HXX
#define _SFXSTYLE_HXX

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _RSCSFX_HXX
#include <rsc/rscsfx.hxx>
#endif

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFXBRDCST_HXX //autogen
#include <svtools/brdcst.hxx>
#endif

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

#ifndef _SFX_STYLE_HRC
#include <svtools/style.hrc>
#endif

class SfxItemSet;
class SfxItemPool;

class SfxStyleSheetBasePool;
class SvStream;

/*=========================================================================

Jeder, der an Intanzen der Klassen SfxStyleSheetBasePool oder am
SfxStyleSheetBase strukturelle �nderungen vornimmt, mu� diese �ber
<SfxStyleSheetBasePool::GetBroadcaster()> broadcasten. Daf�r Gibt es die
Klasse <SfxStyleSheetHint>, die eine Action-Id und einen Pointer auf einen
<SfxStyleSheetBase> erh�lt. Die Actions sind:

#define SFX_STYLESHEET_CREATED      // neu
#define SFX_STYLESHEET_MODIFIED     // ver"andert
#define SFX_STYLESHEET_CHANGED      // ausgetauscht
#define SFX_STYLESHEET_ERASED       // gel"oscht

Es machen bereits die folgenden Methoden von sich aus:

SfxStyleSheetHint(SFX_STYLESHEET_MODIFIED) aus:
   SfxStyleSheetBase::SetName( const String& rName )
   SfxStyleSheetBase::SetParent( const String& rName )
   SfxStyleSheetBase::SetFollow( const String& rName )

SfxSimpleHint(SFX_HINT_DYING) aus:
   SfxStyleSheetBasePool::~SfxStyleSheetBasePool()

SfxStyleSheetHint( SFX_STYLESHEET_CREATED, *p ) aus:
   SfxStyleSheetBasePool::Make( const String& rName,
   SfxStyleFamily eFam, USHORT mask, USHORT nPos)

SfxStyleSheetHint( SFX_STYLESHEET_CHANGED, *pNew ) aus:
   SfxStyleSheetBasePool::Add( SfxStyleSheetBase& rSheet )

SfxStyleSheetHint( SFX_STYLESHEET_ERASED, *p ) aus:
   SfxStyleSheetBasePool::Erase( SfxStyleSheetBase* p )
   SfxStyleSheetBasePool::Clear()

=========================================================================*/

#define VIRTUAL510 virtual

class SVT_DLLPUBLIC SfxStyleSheetBase
{
    friend class SfxStyleSheetBasePool;

protected:
    SfxStyleSheetBasePool&  rPool;          // zugehoeriger Pool
    SfxStyleFamily          nFamily;        // Familie

    UniString                   aName, aParent, aFollow;
    String                  aHelpFile;      // Name der Hilfedatei
    SfxItemSet*             pSet;           // ItemSet
    USHORT                  nMask;          // Flags

    ULONG                   nHelpId;        // Hilfe-ID

    BOOL                    bMySet;         // TRUE: Set loeschen im dtor

    SfxStyleSheetBase( const UniString&, SfxStyleSheetBasePool&,
                        SfxStyleFamily eFam, USHORT mask );
    SfxStyleSheetBase( const SfxStyleSheetBase& );
    virtual ~SfxStyleSheetBase();
    virtual void Load( SvStream&, USHORT );
    virtual void Store( SvStream& );

public:
    TYPEINFO();
    virtual const UniString& GetName() const;
    virtual BOOL SetName( const UniString& );
    virtual const UniString& GetParent() const;
    virtual BOOL SetParent( const UniString& );
    virtual const UniString& GetFollow() const;
    virtual BOOL SetFollow( const UniString& );
    virtual BOOL HasFollowSupport() const;      // Default TRUE
    virtual BOOL HasParentSupport() const;      // Default TRUE
    virtual BOOL HasClearParentSupport() const; // Default FALSE
    virtual BOOL IsUsed() const;                // Default TRUE
        // Default aus dem Itemset; entweder dem uebergebenen
        // oder aus dem per GetItemSet() zurueckgelieferten Set
    virtual UniString GetDescription();
    virtual UniString GetDescription( SfxMapUnit eMetric );

    SfxStyleSheetBasePool& GetPool() { return rPool;   }
    SfxStyleFamily GetFamily() const     { return nFamily; }
    USHORT   GetMask() const     { return nMask; }
    void     SetMask( USHORT mask) { nMask = mask; }
    BOOL   IsUserDefined() const
           { return BOOL( ( nMask & SFXSTYLEBIT_USERDEF) != 0 ); }

    virtual ULONG GetHelpId( String& rFile );
    virtual void   SetHelpId( const String& r, ULONG nId );

    virtual SfxItemSet& GetItemSet();
    virtual USHORT GetVersion() const;
};

//=========================================================================

DECLARE_LIST( SfxStyles, SfxStyleSheetBase* )

//=========================================================================

class SVT_DLLPUBLIC SfxStyleSheetIterator

/*  [Beschreibung]

    Klasse zum Iterieren und Suchen auf einem SfxStyleSheetBasePool.

*/

{
public:
    SfxStyleSheetIterator(SfxStyleSheetBasePool *pBase,
                          SfxStyleFamily eFam, USHORT n=0xFFFF );
    virtual USHORT GetSearchMask() const;
    virtual SfxStyleFamily GetSearchFamily() const;
    virtual USHORT Count();
    virtual SfxStyleSheetBase *operator[](USHORT nIdx);
    virtual SfxStyleSheetBase* First();
    virtual SfxStyleSheetBase* Next();
    virtual SfxStyleSheetBase* Find(const UniString& rStr);
    virtual ~SfxStyleSheetIterator();

protected:

    SfxStyleSheetBasePool*  pBasePool;
    SfxStyleFamily          nSearchFamily;
    USHORT                  nMask;
    BOOL                    SearchUsed() const { return bSearchUsed; }

private:
    USHORT                  GetPos(){return nAktPosition;}
    SVT_DLLPRIVATE BOOL                     IsTrivialSearch();
    SVT_DLLPRIVATE BOOL                     DoesStyleMatch(SfxStyleSheetBase *pStyle);

    void*                   pImp;
    SfxStyleSheetBase*      pAktStyle;
    USHORT                  nAktPosition;
    BOOL                    bSearchUsed;

friend class SfxStyleSheetBasePool;
};

//=========================================================================

class SfxStyleSheetBasePool_Impl;

class SVT_DLLPUBLIC SfxStyleSheetBasePool: public SfxBroadcaster
{
friend class SfxStyleSheetIterator;
friend class SfxStyleSheetBase;

    SfxStyleSheetBasePool_Impl *pImp;

private:
    SVT_DLLPRIVATE BOOL                         Load1_Impl( SvStream& );
    SVT_DLLPRIVATE SfxStyleSheetIterator&      GetIterator_Impl();
protected:
    String                      aAppName;
    SfxItemPool&                rPool;
    SfxStyles                   aStyles;
    SfxStyleFamily              nSearchFamily;
    USHORT                      nMask;

    SfxStyleSheetBase&          Add( SfxStyleSheetBase& );
    void                        ChangeParent( const UniString&, const UniString&, BOOL bVirtual = TRUE );
    virtual SfxStyleSheetBase*  Create( const UniString&, SfxStyleFamily, USHORT );
    virtual SfxStyleSheetBase*  Create( const SfxStyleSheetBase& );

public:
                                SfxStyleSheetBasePool( SfxItemPool& );
                                SfxStyleSheetBasePool( const SfxStyleSheetBasePool& );
                                ~SfxStyleSheetBasePool();

    static String               GetStreamName();

    const String&               GetAppName() const { return aAppName;   }

    SfxItemPool&                GetPool();
    const SfxItemPool&          GetPool() const;

    virtual SfxStyleSheetIterator* CreateIterator(SfxStyleFamily, USHORT nMask);
    virtual USHORT              Count();
    virtual SfxStyleSheetBase*  operator[](USHORT nIdx);

    virtual SfxStyleSheetBase&  Make(const UniString&,
                                     SfxStyleFamily eFam,
                                     USHORT nMask = 0xffff ,
                                     USHORT nPos = 0xffff);

    VIRTUAL510 void             Replace(
        SfxStyleSheetBase& rSource, SfxStyleSheetBase& rTarget );
    virtual SfxStyleSheetBase * Remove( SfxStyleSheetBase* );
    virtual void                Insert( SfxStyleSheetBase* );

    virtual void                Erase( SfxStyleSheetBase* );
    virtual void                Clear();

    SfxStyleSheetBasePool&      operator=( const SfxStyleSheetBasePool& );
    SfxStyleSheetBasePool&      operator+=( const SfxStyleSheetBasePool& );

    SfxStyles&                  GetStyles() { return aStyles; }
    virtual SfxStyleSheetBase*  First();
    virtual SfxStyleSheetBase*  Next();
    virtual SfxStyleSheetBase*  Find( const UniString&,
                                      SfxStyleFamily eFam, USHORT n=0xFFFF );
    virtual BOOL                SetParent(SfxStyleFamily eFam,
                                          const UniString &rStyle,
                                          const UniString &rParent);

    SfxStyleSheetBase*          Find(const UniString& rStr)
                                { return Find(rStr, nSearchFamily, nMask); }

    void                        SetSearchMask(SfxStyleFamily eFam, USHORT n=0xFFFF );
    USHORT                      GetSearchMask() const;
    SfxStyleFamily              GetSearchFamily() const  { return nSearchFamily; }

    BOOL                        Load( SvStream& );
    BOOL                        Store( SvStream&, BOOL bUsed = TRUE );
};

//=========================================================================

class SVT_DLLPUBLIC SfxStyleSheet: public SfxStyleSheetBase,
                     public SfxListener, public SfxBroadcaster
{
public:
                        TYPEINFO();

                        SfxStyleSheet( const UniString&, SfxStyleSheetBasePool&, SfxStyleFamily, USHORT );
                        SfxStyleSheet( const SfxStyleSheet& );

    virtual             ~SfxStyleSheet();

    virtual void        SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
                                const SfxHint& rHint, const TypeId& rHintType );
    virtual BOOL        SetParent( const UniString& );
};

//=========================================================================

class SVT_DLLPUBLIC SfxStyleSheetPool: public SfxStyleSheetBasePool
{
protected:
    using SfxStyleSheetBasePool::Create;
    virtual SfxStyleSheetBase* Create(const UniString&, SfxStyleFamily, USHORT mask);
    virtual SfxStyleSheetBase* Create(const SfxStyleSheet &);

public:
    SfxStyleSheetPool( SfxItemPool& );

//  virtual BOOL CopyTo(SfxStyleSheetPool &rDest, const String &rSourceName);
};

//=========================================================================

#define SFX_STYLESHEET_CREATED       1  // neu
#define SFX_STYLESHEET_MODIFIED      2  // ver"andert
#define SFX_STYLESHEET_CHANGED       3  // gel"oscht und neu (ausgetauscht)
#define SFX_STYLESHEET_ERASED        4  // gel"oscht
#define SFX_STYLESHEET_INDESTRUCTION 5  // wird gerade entfernt

#define SFX_STYLESHEETPOOL_CHANGES  1  // Aenderungen, die den Zustand
                                       // des Pools anedern, aber nicht
                                       // ueber die STYLESHEET Hints
                                       // verschickt werden sollen.

//========================================================================

class SVT_DLLPUBLIC SfxStyleSheetPoolHint : public SfxHint
{
    USHORT nHint;

public:
    TYPEINFO();

                        SfxStyleSheetPoolHint(USHORT nArgHint) :  nHint(nArgHint){}
    USHORT              GetHint() const
                        { return nHint; }
};

//=========================================================================

class SVT_DLLPUBLIC SfxStyleSheetHint: public SfxHint
{
    SfxStyleSheetBase*  pStyleSh;
    USHORT              nHint;

public:
                        TYPEINFO();

                        SfxStyleSheetHint( USHORT );
                        SfxStyleSheetHint( USHORT, SfxStyleSheetBase& );
    SfxStyleSheetBase*  GetStyleSheet() const
                        { return pStyleSh; }
    USHORT              GetHint() const
                        { return nHint; }
};

class SVT_DLLPUBLIC SfxStyleSheetHintExtended: public SfxStyleSheetHint
{
    String              aName;

public:
                        TYPEINFO();

                        SfxStyleSheetHintExtended(
                            USHORT, const String& rOld );
                        SfxStyleSheetHintExtended(
                            USHORT, const String& rOld,
                            SfxStyleSheetBase& );
    const String&       GetOldName() { return aName; }
};

#endif

<commit_msg>INTEGRATION: CWS impresstables2 (1.2.128); FILE MERGED 2008/01/30 13:27:43 cl 1.2.128.6: RESYNC: (1.2-1.3); FILE MERGED 2008/01/30 12:05:58 cl 1.2.128.5: #i68103# constructor hack to make implinheritancehelper merry 2008/01/30 11:52:32 cl 1.2.128.4: #i68103# export SfxUnoStyleSheet 2008/01/30 11:21:38 cl 1.2.128.3: #i68103# added XUnoTunnel to SfxUnoStyleSheet for safer conversion 2008/01/29 18:00:40 cl 1.2.128.2: #i68103# added SfxUnoStyleSheet to fix a dynamic_cast issue under linux 2007/07/26 21:32:35 cl 1.2.128.1: #i68103# reworked styles to use refcounting<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: style.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 13:08:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SFXSTYLE_HXX
#define _SFXSTYLE_HXX

#include <com/sun/star/style/XStyle.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>

#include <rtl/ref.hxx>
#include <vector>
#include <comphelper/weak.hxx>
#include <cppuhelper/implbase2.hxx>

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _RSCSFX_HXX
#include <rsc/rscsfx.hxx>
#endif

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFXBRDCST_HXX //autogen
#include <svtools/brdcst.hxx>
#endif

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

#ifndef _SFX_STYLE_HRC
#include <svtools/style.hrc>
#endif

class SfxItemSet;
class SfxItemPool;

class SfxStyleSheetBasePool;
class SvStream;

/*
Everyone changing instances of SfxStyleSheetBasePool or SfxStyleSheetBase
mußt broadcast this using <SfxStyleSheetBasePool::GetBroadcaster()> broadcasten.
The class <SfxStyleSheetHint> is used for this, it contains an Action-Id and a
pointer to the <SfxStyleSheetBase>. The actions are:

#define SFX_STYLESHEET_CREATED      // style is created
#define SFX_STYLESHEET_MODIFIED     // style is modified
#define SFX_STYLESHEET_CHANGED      // style is replaced
#define SFX_STYLESHEET_ERASED       // style is deleted

The following methods already broadcast themself

SfxStyleSheetHint(SFX_STYLESHEET_MODIFIED) from:
   SfxStyleSheetBase::SetName( const String& rName )
   SfxStyleSheetBase::SetParent( const String& rName )
   SfxStyleSheetBase::SetFollow( const String& rName )

SfxSimpleHint(SFX_HINT_DYING) from:
   SfxStyleSheetBasePool::~SfxStyleSheetBasePool()

SfxStyleSheetHint( SFX_STYLESHEET_CREATED, *p ) from:
   SfxStyleSheetBasePool::Make( const String& rName,
   SfxStyleFamily eFam, USHORT mask, USHORT nPos)

SfxStyleSheetHint( SFX_STYLESHEET_CHANGED, *pNew ) from:
   SfxStyleSheetBasePool::Add( SfxStyleSheetBase& rSheet )

SfxStyleSheetHint( SFX_STYLESHEET_ERASED, *p ) from:
   SfxStyleSheetBasePool::Erase( SfxStyleSheetBase* p )
   SfxStyleSheetBasePool::Clear()
*/

#define VIRTUAL510 virtual

class SVT_DLLPUBLIC SfxStyleSheetBase : public comphelper::OWeakTypeObject
{
    friend class SfxStyleSheetBasePool;

protected:
    SfxStyleSheetBasePool&  rPool;          // zugehoeriger Pool
    SfxStyleFamily          nFamily;        // Familie

    UniString               aName, aParent, aFollow;
    rtl::OUString           maDisplayName;
    String                  aHelpFile;      // Name der Hilfedatei
    SfxItemSet*             pSet;           // ItemSet
    USHORT                  nMask;          // Flags

    ULONG                   nHelpId;        // Hilfe-ID

    BOOL                    bMySet;         // TRUE: Set loeschen im dtor

    SfxStyleSheetBase(); // do not use!
    SfxStyleSheetBase( const UniString&, SfxStyleSheetBasePool&, SfxStyleFamily eFam, USHORT mask );
    SfxStyleSheetBase( const SfxStyleSheetBase& );
    virtual ~SfxStyleSheetBase();
    virtual void Load( SvStream&, USHORT );
    virtual void Store( SvStream& );

public:
    TYPEINFO();

    // returns the internal name of this style
    virtual const UniString& GetName() const;

    // sets the internal name of this style
    virtual BOOL SetName( const UniString& );

    /** returns the display name of this style, it is used at the user interface.
        If the display name is empty, this method returns the internal name. */
    virtual rtl::OUString GetDisplayName() const;

    // sets the display name of this style
    virtual void SetDisplayName( const rtl::OUString& );

    virtual const UniString& GetParent() const;
    virtual BOOL SetParent( const UniString& );
    virtual const UniString& GetFollow() const;
    virtual BOOL SetFollow( const UniString& );
    virtual BOOL HasFollowSupport() const;      // Default TRUE
    virtual BOOL HasParentSupport() const;      // Default TRUE
    virtual BOOL HasClearParentSupport() const; // Default FALSE
    virtual BOOL IsUsed() const;                // Default TRUE
        // Default aus dem Itemset; entweder dem uebergebenen
        // oder aus dem per GetItemSet() zurueckgelieferten Set
    virtual UniString GetDescription();
    virtual UniString GetDescription( SfxMapUnit eMetric );

    SfxStyleSheetBasePool& GetPool() { return rPool;   }
    SfxStyleFamily GetFamily() const     { return nFamily; }
    USHORT   GetMask() const     { return nMask; }
    void     SetMask( USHORT mask) { nMask = mask; }
    BOOL   IsUserDefined() const
           { return BOOL( ( nMask & SFXSTYLEBIT_USERDEF) != 0 ); }

    virtual ULONG GetHelpId( String& rFile );
    virtual void   SetHelpId( const String& r, ULONG nId );

    virtual SfxItemSet& GetItemSet();
    virtual USHORT GetVersion() const;
};

//=========================================================================

typedef std::vector< rtl::Reference< SfxStyleSheetBase > > SfxStyles;

//=========================================================================

class SVT_DLLPUBLIC SfxStyleSheetIterator

/*  [Beschreibung]

    Klasse zum Iterieren und Suchen auf einem SfxStyleSheetBasePool.

*/

{
public:
    SfxStyleSheetIterator(SfxStyleSheetBasePool *pBase,
                          SfxStyleFamily eFam, USHORT n=0xFFFF );
    virtual USHORT GetSearchMask() const;
    virtual SfxStyleFamily GetSearchFamily() const;
    virtual USHORT Count();
    virtual SfxStyleSheetBase *operator[](USHORT nIdx);
    virtual SfxStyleSheetBase* First();
    virtual SfxStyleSheetBase* Next();
    virtual SfxStyleSheetBase* Find(const UniString& rStr);
    virtual ~SfxStyleSheetIterator();

protected:

    SfxStyleSheetBasePool*  pBasePool;
    SfxStyleFamily          nSearchFamily;
    USHORT                  nMask;
    BOOL                    SearchUsed() const { return bSearchUsed; }

private:
    USHORT                  GetPos(){return nAktPosition;}
    SVT_DLLPRIVATE BOOL                     IsTrivialSearch();
    SVT_DLLPRIVATE BOOL                     DoesStyleMatch(SfxStyleSheetBase *pStyle);

    void*                   pImp;
    SfxStyleSheetBase*      pAktStyle;
    USHORT                  nAktPosition;
    BOOL                    bSearchUsed;

friend class SfxStyleSheetBasePool;
};

//=========================================================================

class SfxStyleSheetBasePool_Impl;

class SVT_DLLPUBLIC SfxStyleSheetBasePool: public SfxBroadcaster, public comphelper::OWeakTypeObject
{
friend class SfxStyleSheetIterator;
friend class SfxStyleSheetBase;

    SfxStyleSheetBasePool_Impl *pImp;

private:
    SVT_DLLPRIVATE BOOL                         Load1_Impl( SvStream& );
    SVT_DLLPRIVATE SfxStyleSheetIterator&      GetIterator_Impl();
protected:
    String                      aAppName;
    SfxItemPool&                rPool;
    SfxStyles                   aStyles;
    SfxStyleFamily              nSearchFamily;
    USHORT                      nMask;

    SfxStyleSheetBase&          Add( SfxStyleSheetBase& );
    void                        ChangeParent( const UniString&, const UniString&, BOOL bVirtual = TRUE );
    virtual SfxStyleSheetBase*  Create( const UniString&, SfxStyleFamily, USHORT );
    virtual SfxStyleSheetBase*  Create( const SfxStyleSheetBase& );

                                ~SfxStyleSheetBasePool();

public:
                                SfxStyleSheetBasePool( SfxItemPool& );
                                SfxStyleSheetBasePool( const SfxStyleSheetBasePool& );

    static String               GetStreamName();

    const String&               GetAppName() const { return aAppName;   }

    SfxItemPool&                GetPool();
    const SfxItemPool&          GetPool() const;

    virtual SfxStyleSheetIterator* CreateIterator(SfxStyleFamily, USHORT nMask);
    virtual USHORT              Count();
    virtual SfxStyleSheetBase*  operator[](USHORT nIdx);

    virtual SfxStyleSheetBase&  Make(const UniString&,
                                     SfxStyleFamily eFam,
                                     USHORT nMask = 0xffff ,
                                     USHORT nPos = 0xffff);

    virtual void             Replace(
        SfxStyleSheetBase& rSource, SfxStyleSheetBase& rTarget );

    virtual void                Remove( SfxStyleSheetBase* );
    virtual void                Insert( SfxStyleSheetBase* );

    virtual void                Clear();

    SfxStyleSheetBasePool&      operator=( const SfxStyleSheetBasePool& );
    SfxStyleSheetBasePool&      operator+=( const SfxStyleSheetBasePool& );

    const SfxStyles&            GetStyles();
    virtual SfxStyleSheetBase*  First();
    virtual SfxStyleSheetBase*  Next();
    virtual SfxStyleSheetBase*  Find( const UniString&, SfxStyleFamily eFam, USHORT n=0xFFFF );

    virtual BOOL                SetParent(SfxStyleFamily eFam,
                                          const UniString &rStyle,
                                          const UniString &rParent);

    SfxStyleSheetBase*          Find(const UniString& rStr)
                                { return Find(rStr, nSearchFamily, nMask); }

    void                        SetSearchMask(SfxStyleFamily eFam, USHORT n=0xFFFF );
    USHORT                      GetSearchMask() const;
    SfxStyleFamily              GetSearchFamily() const  { return nSearchFamily; }

    BOOL                        Load( SvStream& );
    BOOL                        Store( SvStream&, BOOL bUsed = TRUE );
};

//=========================================================================

class SVT_DLLPUBLIC SfxStyleSheet: public SfxStyleSheetBase,
                     public SfxListener, public SfxBroadcaster
{
public:
                        TYPEINFO();

                        SfxStyleSheet( const UniString&, const SfxStyleSheetBasePool&, SfxStyleFamily, USHORT );
                        SfxStyleSheet( const SfxStyleSheet& );

    virtual void        SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
                                const SfxHint& rHint, const TypeId& rHintType );
    virtual BOOL        SetParent( const UniString& );

protected:
    SfxStyleSheet(); // do not use!
    virtual             ~SfxStyleSheet();
};

//=========================================================================

class SVT_DLLPUBLIC SfxStyleSheetPool: public SfxStyleSheetBasePool
{
protected:
    using SfxStyleSheetBasePool::Create;
    virtual SfxStyleSheetBase* Create(const UniString&, SfxStyleFamily, USHORT mask);
    virtual SfxStyleSheetBase* Create(const SfxStyleSheet &);

public:
    SfxStyleSheetPool( SfxItemPool const& );

//  virtual BOOL CopyTo(SfxStyleSheetPool &rDest, const String &rSourceName);
};

//=========================================================================

#define SFX_STYLESHEET_CREATED       1  // neu
#define SFX_STYLESHEET_MODIFIED      2  // ver"andert
#define SFX_STYLESHEET_CHANGED       3  // gel"oscht und neu (ausgetauscht)
#define SFX_STYLESHEET_ERASED        4  // gel"oscht
#define SFX_STYLESHEET_INDESTRUCTION 5  // wird gerade entfernt

#define SFX_STYLESHEETPOOL_CHANGES  1  // Aenderungen, die den Zustand
                                       // des Pools anedern, aber nicht
                                       // ueber die STYLESHEET Hints
                                       // verschickt werden sollen.

//========================================================================

class SVT_DLLPUBLIC SfxStyleSheetPoolHint : public SfxHint
{
    USHORT nHint;

public:
    TYPEINFO();

                        SfxStyleSheetPoolHint(USHORT nArgHint) :  nHint(nArgHint){}
    USHORT              GetHint() const
                        { return nHint; }
};

//=========================================================================

class SVT_DLLPUBLIC SfxStyleSheetHint: public SfxHint
{
    SfxStyleSheetBase*  pStyleSh;
    USHORT              nHint;

public:
                        TYPEINFO();

                        SfxStyleSheetHint( USHORT );
                        SfxStyleSheetHint( USHORT, SfxStyleSheetBase& );
    SfxStyleSheetBase*  GetStyleSheet() const
                        { return pStyleSh; }
    USHORT              GetHint() const
                        { return nHint; }
};

class SVT_DLLPUBLIC SfxStyleSheetHintExtended: public SfxStyleSheetHint
{
    String              aName;

public:
                        TYPEINFO();

                        SfxStyleSheetHintExtended(
                            USHORT, const String& rOld );
                        SfxStyleSheetHintExtended(
                            USHORT, const String& rOld,
                            SfxStyleSheetBase& );
    const String&       GetOldName() { return aName; }
};

class SVT_DLLPUBLIC SfxUnoStyleSheet : public ::cppu::ImplInheritanceHelper2< SfxStyleSheet, ::com::sun::star::style::XStyle, ::com::sun::star::lang::XUnoTunnel >
{
public:
    SfxUnoStyleSheet( const UniString& _rName, const SfxStyleSheetBasePool& _rPool, SfxStyleFamily _eFamily, USHORT _nMaske );
    SfxUnoStyleSheet( const SfxStyleSheet& _rSheet );

    static SfxUnoStyleSheet* getUnoStyleSheet( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >& xStyle );

    // XUnoTunnel
    virtual ::sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);

private:
    SfxUnoStyleSheet(); // not implemented

    static const ::com::sun::star::uno::Sequence< ::sal_Int8 >& getIdentifier();
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: imap3.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:59:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "imap.hxx"

#include <tools/debug.hxx>

/******************************************************************************
|*
|* Ctor
|*
\******************************************************************************/

IMapCompat::IMapCompat( SvStream& rStm, const USHORT nStreamMode ) :
            pRWStm      ( &rStm ),
            nStmMode    ( nStreamMode )
{
    DBG_ASSERT( nStreamMode == STREAM_READ || nStreamMode == STREAM_WRITE, "Wrong Mode!" );

    if ( !pRWStm->GetError() )
    {
        if ( nStmMode == STREAM_WRITE )
        {
            nCompatPos = pRWStm->Tell();
            pRWStm->SeekRel( 4 );
            nTotalSize = nCompatPos + 4;
        }
        else
        {
            UINT32 nTotalSizeTmp;
            *pRWStm >> nTotalSizeTmp;
            nTotalSize = nTotalSizeTmp;
            nCompatPos = pRWStm->Tell();
        }
    }
}

/******************************************************************************
|*
|* Dtor
|*
\******************************************************************************/

IMapCompat::~IMapCompat()
{
    if ( !pRWStm->GetError() )
    {
        if ( nStmMode == STREAM_WRITE )
        {
            const ULONG nEndPos = pRWStm->Tell();

            pRWStm->Seek( nCompatPos );
            *pRWStm << (UINT32) ( nEndPos - nTotalSize );
            pRWStm->Seek( nEndPos );
        }
        else
        {
            const ULONG nReadSize = pRWStm->Tell() - nCompatPos;

            if ( nTotalSize > nReadSize )
                pRWStm->SeekRel( nTotalSize - nReadSize );
        }
    }
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1110); FILE MERGED 2005/09/05 14:53:35 rt 1.1.1.1.1110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: imap3.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:19:48 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "imap.hxx"

#include <tools/debug.hxx>

/******************************************************************************
|*
|* Ctor
|*
\******************************************************************************/

IMapCompat::IMapCompat( SvStream& rStm, const USHORT nStreamMode ) :
            pRWStm      ( &rStm ),
            nStmMode    ( nStreamMode )
{
    DBG_ASSERT( nStreamMode == STREAM_READ || nStreamMode == STREAM_WRITE, "Wrong Mode!" );

    if ( !pRWStm->GetError() )
    {
        if ( nStmMode == STREAM_WRITE )
        {
            nCompatPos = pRWStm->Tell();
            pRWStm->SeekRel( 4 );
            nTotalSize = nCompatPos + 4;
        }
        else
        {
            UINT32 nTotalSizeTmp;
            *pRWStm >> nTotalSizeTmp;
            nTotalSize = nTotalSizeTmp;
            nCompatPos = pRWStm->Tell();
        }
    }
}

/******************************************************************************
|*
|* Dtor
|*
\******************************************************************************/

IMapCompat::~IMapCompat()
{
    if ( !pRWStm->GetError() )
    {
        if ( nStmMode == STREAM_WRITE )
        {
            const ULONG nEndPos = pRWStm->Tell();

            pRWStm->Seek( nCompatPos );
            *pRWStm << (UINT32) ( nEndPos - nTotalSize );
            pRWStm->Seek( nEndPos );
        }
        else
        {
            const ULONG nReadSize = pRWStm->Tell() - nCompatPos;

            if ( nTotalSize > nReadSize )
                pRWStm->SeekRel( nTotalSize - nReadSize );
        }
    }
}

<|endoftext|>