<commit_before>/* This file exists to provide some stat monitors for process statistics and the like. */

#include <vector>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "perfmon.hpp"
#include "logger.hpp"

/* Class to represent and parse the contents of /proc/[pid]/stat */

struct proc_pid_stat_t {
    int pid;
    char name[500];
    char state;
    int ppid, pgrp, session, tty_nr, tpgid;
    unsigned int flags;
    unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime;
    long int cutime, cstime, priority, nice, num_threads, itrealvalue;
    long long unsigned int starttime;
    long unsigned int vsize;
    long int rss;
    long unsigned int rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,
        sigignore, sigcatch, wchan, nswap, cnswap;
    int exit_signal, processor;
    unsigned int rt_priority, policy;
    long long unsigned int delayacct_blkio_ticks;
    long unsigned int guest_time;
    long int cguest_time;

    bool read_stats(pid_t pid) {
        char path[100];
        snprintf(path, sizeof(path), "/proc/%d/stat", pid);
        return read(path);
    }

    bool read_task_stats(pid_t pid, pid_t tid) {
        char path[100];
        snprintf(path, sizeof(path), "/proc/%d/task/%d/stat", pid, tid);
        return read(path);
    }

private:
    bool read(char * path) {
        int stat_file = open(path, O_RDONLY);
        if (stat_file == -1) {
            logWRN("Could not open '%s': %s (errno = %d)", path, strerror(errno), errno);
            return false;
        }

        char buffer[1000];
        int res = ::read(stat_file, buffer, sizeof(buffer));
        if (res <= 0) {
            logWRN("Could not read '%s': %s (errno = %d)", path, strerror(errno), errno);
            close(stat_file);
            return false;
        }

        buffer[res] = '\0';

        close(stat_file);

        // TODO rewrite this mess to use something more safe and sane, e.g. iostreams
        const int items_to_parse = 44;
        int res2 = sscanf(buffer, "%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld "
            "%ld %ld %ld %ld %llu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %d "
            "%d %u %u %u %u %llu %lu %ld",
            &pid, name, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid,
            &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,
            &cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,
            &starttime, &vsize, &rss, &rsslim, &startcode, &endcode, &startstack,
            &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan,
            &nswap, &cnswap, &exit_signal, &processor, &rt_priority, &processor,
            &rt_priority, &policy, &delayacct_blkio_ticks, &guest_time, &cguest_time);
        if (res2 != items_to_parse) {
            logWRN("Could not parse '%s': expected to parse %d items, parsed %d. Buffer contents: %s", path, items_to_parse, res2, buffer);
            return false;
        }
        return true;
    }
};

/* perfmon_system_t is used to monitor system stats that do not need to be polled. */

class perfmon_system_t :
    public perfmon_t
{
    void *begin_stats() {
        return NULL;
    }
    void visit_stats(void *) {
    }
    void end_stats(void *, perfmon_stats_t *dest) {
        proc_pid_stat_t pid_stat;
        if (pid_stat.read_stats(getpid())) {
            (*dest)["pid"] = format(pid_stat.pid);
            (*dest)["memory_virtual[bytes]"] = format(pid_stat.vsize);
            (*dest)["memory_real[bytes]"] = format(pid_stat.rss * sysconf(_SC_PAGESIZE));
        }
    }
} pm_system;

/* Some of the stats need to be polled periodically. Call this function periodically on each
thread to ensure that stats are up to date. It takes a void* so that it can be called as a timer
callback. */

perfmon_sampler_t
    pm_cpu_user("cpu_user", secs_to_ticks(5)),
    pm_cpu_system("cpu_system", secs_to_ticks(5)),
    pm_memory_faults("memory_faults", secs_to_ticks(5));

static __thread proc_pid_stat_t last_stats;
static __thread ticks_t last_ticks = 0;

void poll_system_stats(void *) {
    pid_t tid = syscall(SYS_gettid);

    proc_pid_stat_t current_stats;
    current_stats.read_task_stats(getpid(), tid);
    ticks_t current_ticks = get_ticks();

    if (last_ticks == 0) {
        last_stats = current_stats;
        last_ticks = current_ticks;
    } else if (current_ticks > last_ticks + secs_to_ticks(1)) {
        double realtime_elapsed = ticks_to_secs(current_ticks - last_ticks) * sysconf(_SC_CLK_TCK);
        pm_cpu_user.record((current_stats.utime - last_stats.utime) / realtime_elapsed);
        pm_cpu_system.record((current_stats.stime - last_stats.stime) / realtime_elapsed);
        pm_memory_faults.record((current_stats.majflt - last_stats.majflt) / realtime_elapsed);

        last_stats = current_stats;
        last_ticks = current_ticks;
    }
}

<commit_msg>Added a third CPU usage monitor for combined user+system usage.<commit_after>/* This file exists to provide some stat monitors for process statistics and the like. */

#include <vector>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "perfmon.hpp"
#include "logger.hpp"

/* Class to represent and parse the contents of /proc/[pid]/stat */

struct proc_pid_stat_t {
    int pid;
    char name[500];
    char state;
    int ppid, pgrp, session, tty_nr, tpgid;
    unsigned int flags;
    unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime;
    long int cutime, cstime, priority, nice, num_threads, itrealvalue;
    long long unsigned int starttime;
    long unsigned int vsize;
    long int rss;
    long unsigned int rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,
        sigignore, sigcatch, wchan, nswap, cnswap;
    int exit_signal, processor;
    unsigned int rt_priority, policy;
    long long unsigned int delayacct_blkio_ticks;
    long unsigned int guest_time;
    long int cguest_time;

    bool read_stats(pid_t pid) {
        char path[100];
        snprintf(path, sizeof(path), "/proc/%d/stat", pid);
        return read(path);
    }

    bool read_task_stats(pid_t pid, pid_t tid) {
        char path[100];
        snprintf(path, sizeof(path), "/proc/%d/task/%d/stat", pid, tid);
        return read(path);
    }

private:
    bool read(char * path) {
        int stat_file = open(path, O_RDONLY);
        if (stat_file == -1) {
            logWRN("Could not open '%s': %s (errno = %d)", path, strerror(errno), errno);
            return false;
        }

        char buffer[1000];
        int res = ::read(stat_file, buffer, sizeof(buffer));
        if (res <= 0) {
            logWRN("Could not read '%s': %s (errno = %d)", path, strerror(errno), errno);
            close(stat_file);
            return false;
        }

        buffer[res] = '\0';

        close(stat_file);

        // TODO rewrite this mess to use something more safe and sane, e.g. iostreams
        const int items_to_parse = 44;
        int res2 = sscanf(buffer, "%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld "
            "%ld %ld %ld %ld %llu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %d "
            "%d %u %u %u %u %llu %lu %ld",
            &pid, name, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid,
            &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,
            &cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,
            &starttime, &vsize, &rss, &rsslim, &startcode, &endcode, &startstack,
            &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan,
            &nswap, &cnswap, &exit_signal, &processor, &rt_priority, &processor,
            &rt_priority, &policy, &delayacct_blkio_ticks, &guest_time, &cguest_time);
        if (res2 != items_to_parse) {
            logWRN("Could not parse '%s': expected to parse %d items, parsed %d. Buffer contents: %s", path, items_to_parse, res2, buffer);
            return false;
        }
        return true;
    }
};

/* perfmon_system_t is used to monitor system stats that do not need to be polled. */

class perfmon_system_t :
    public perfmon_t
{
    void *begin_stats() {
        return NULL;
    }
    void visit_stats(void *) {
    }
    void end_stats(void *, perfmon_stats_t *dest) {
        proc_pid_stat_t pid_stat;
        if (pid_stat.read_stats(getpid())) {
            (*dest)["pid"] = format(pid_stat.pid);
            (*dest)["memory_virtual[bytes]"] = format(pid_stat.vsize);
            (*dest)["memory_real[bytes]"] = format(pid_stat.rss * sysconf(_SC_PAGESIZE));
        }
    }
} pm_system;

/* Some of the stats need to be polled periodically. Call this function periodically on each
thread to ensure that stats are up to date. It takes a void* so that it can be called as a timer
callback. */

perfmon_sampler_t
    pm_cpu_user("cpu_user", secs_to_ticks(5)),
    pm_cpu_system("cpu_system", secs_to_ticks(5)),
    pm_cpu_combined("cpu_combined", secs_to_ticks(5)),
    pm_memory_faults("memory_faults", secs_to_ticks(5));

static __thread proc_pid_stat_t last_stats;
static __thread ticks_t last_ticks = 0;

void poll_system_stats(void *) {
    pid_t tid = syscall(SYS_gettid);

    proc_pid_stat_t current_stats;
    current_stats.read_task_stats(getpid(), tid);
    ticks_t current_ticks = get_ticks();

    if (last_ticks == 0) {
        last_stats = current_stats;
        last_ticks = current_ticks;
    } else if (current_ticks > last_ticks + secs_to_ticks(1)) {
        double realtime_elapsed = ticks_to_secs(current_ticks - last_ticks) * sysconf(_SC_CLK_TCK);
        pm_cpu_user.record((current_stats.utime - last_stats.utime) / realtime_elapsed);
        pm_cpu_system.record((current_stats.stime - last_stats.stime) / realtime_elapsed);
        pm_cpu_combined.record(
            (current_stats.utime - last_stats.utime +
             current_stats.stime - last_stats.stime) /
             realtime_elapsed);
        pm_memory_faults.record((current_stats.majflt - last_stats.majflt) / realtime_elapsed);

        last_stats = current_stats;
        last_ticks = current_ticks;
    }
}

<|endoftext|>


<commit_before>// This file is part of the Orbbec Astra SDK [https://orbbec3d.com]
// Copyright (c) 2015 Orbbec 3D
//
// Licensed under the Apache License, Version 2.0 (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.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.
//
// Be excellent to each other.
#ifndef ASTRA_LOGGING_H
#define ASTRA_LOGGING_H

// TODO valgrind will go bananas with the default crash handler enabled
// #define ELPP_DISABLE_DEFAULT_CRASH_HANDLING
#define ELPP_NO_DEFAULT_LOG_FILE

// enable stacktraces for GCC/Clang on *nixes
#if ! defined(__ANDROID__) && ! defined(_MSC_VER)
#define ELPP_STACKTRACE_ON_CRASH
#endif

#include "easylogging++.h"
#include <astra_core/capi/astra_types.h>

#define INITIALIZE_LOGGING INITIALIZE_EASYLOGGINGPP

namespace astra {
    void initialize_logging(const char* logFilePath, astra_log_severity_t severity, bool consoleOutput, bool fileOutput);
}

#endif /* ASTRA_LOGGING_H */
<commit_msg>Mute warning generated by easylogging code<commit_after>// This file is part of the Orbbec Astra SDK [https://orbbec3d.com]
// Copyright (c) 2015 Orbbec 3D
//
// Licensed under the Apache License, Version 2.0 (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.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.
//
// Be excellent to each other.
#ifndef ASTRA_LOGGING_H
#define ASTRA_LOGGING_H

// TODO valgrind will go bananas with the default crash handler enabled
// #define ELPP_DISABLE_DEFAULT_CRASH_HANDLING
#define ELPP_NO_DEFAULT_LOG_FILE

// enable stacktraces for GCC/Clang on *nixes
#if ! defined(__ANDROID__) && ! defined(_MSC_VER)
#define ELPP_STACKTRACE_ON_CRASH
#endif

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpessimizing-move"
#endif
#include "easylogging++.h"
#ifdef __clang__
#pragma clang diagnostic pop
#endif

#include <astra_core/capi/astra_types.h>

#define INITIALIZE_LOGGING INITIALIZE_EASYLOGGINGPP

namespace astra {
    void initialize_logging(const char* logFilePath, astra_log_severity_t severity, bool consoleOutput, bool fileOutput);
}

#endif /* ASTRA_LOGGING_H */
<|endoftext|>


<commit_before>/*
 * filter_qtext.cpp -- text overlay filter
 * Copyright (c) 2018 Meltytech, LLC
 *
 * This 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
 */

#include "common.h"
#include <framework/mlt.h>
#include <framework/mlt_log.h>
#include <QPainter>
#include <QString>

static QRectF get_text_path( QPainterPath* qpath, mlt_properties filter_properties, const char* text )
{
	int outline = mlt_properties_get_int( filter_properties, "outline" );
	char halign = mlt_properties_get( filter_properties, "halign" )[0];
	char style = mlt_properties_get( filter_properties, "style" )[0];
	int pad = mlt_properties_get_int( filter_properties, "pad" );
	int offset = pad + ( outline / 2 );
	int width = 0;
	int height = 0;

	qpath->setFillRule( Qt::WindingFill );

	// Get the strings to display
	QString s = QString::fromUtf8(text);
	QStringList lines = s.split( "\n" );

	// Configure the font
	QFont font;
	font.setPixelSize( mlt_properties_get_int( filter_properties, "size" ) );
	font.setFamily( mlt_properties_get( filter_properties, "family" ) );
	font.setWeight( ( mlt_properties_get_int( filter_properties, "weight" ) / 10 ) -1 );
	switch( style )
	{
	case 'i':
	case 'I':
		font.setStyle( QFont::StyleItalic );
		break;
	}
	QFontMetrics fm( font );

	// Determine the text rectangle size
	height = fm.lineSpacing() * lines.size();
	for( int i = 0; i < lines.size(); ++i )
	{
		const QString line = lines[i];
		int line_width = fm.width(line);
		int bearing = (line.size() > 0) ? fm.leftBearing(line.at(0)) : 0;
		if (bearing < 0)
			line_width -= bearing;
		bearing = (line.size() > 0) ? fm.rightBearing(line.at(line.size() - 1)) : 0;
		if (bearing < 0)
			line_width -= bearing;
		if (line_width > width)
			width = line_width;
	}

	// Lay out the text in the path
	int x = 0;
	int y = fm.ascent() + offset;
	for( int i = 0; i < lines.size(); ++i )
	{
		QString line = lines.at(i);
		x = offset;
		int line_width = fm.width(line);
		int bearing = (line.size() > 0)? fm.leftBearing(line.at(0)) : 0;

		if (bearing < 0) {
			line_width -= bearing;
			x -= bearing;
		}
		bearing = (line.size() > 0)? fm.rightBearing(line.at(line.size() - 1)) : 0;
		if (bearing < 0)
			line_width -= bearing;

		switch( halign )
		{
			default:
			case 'l':
			case 'L':
				break;
			case 'c':
			case 'C':
				x += ( width - line_width ) / 2;
				break;
			case 'r':
			case 'R':
				x += width - line_width;
				break;
		}
		qpath->addText( x, y, font, line );
		y += fm.lineSpacing();
	}

	// Account for outline and pad
	width += offset * 2;
	height += offset * 2;
	// Sanity check
	if( width == 0 ) width = 1;
	height += 2; // I found some fonts whose descenders get cut off.

	return QRectF( 0, 0, width, height );
}

static QColor get_qcolor( mlt_properties filter_properties, const char* name )
{
	mlt_color color = mlt_properties_get_color( filter_properties, name );
	return QColor( color.r, color.g, color.b, color.a );
}

static QPen get_qpen( mlt_properties filter_properties )
{
	QColor color;
	int outline = mlt_properties_get_int( filter_properties, "outline" );
	QPen pen;

	pen.setWidth( outline );
	if( outline )
	{
		color = get_qcolor( filter_properties, "olcolour" );
	}
	else
	{
		color = get_qcolor( filter_properties, "bgcolour" );
	}
	pen.setColor( color );

	return pen;
}

static QBrush get_qbrush( mlt_properties filter_properties )
{
	QColor color = get_qcolor( filter_properties, "fgcolour" );
	return QBrush ( color );
}

static void transform_painter( QPainter* painter, mlt_rect frame_rect, QRectF path_rect, mlt_properties filter_properties, mlt_profile profile )
{
	qreal sx = 1.0;
	qreal sy = mlt_profile_sar( profile );
	qreal path_width = path_rect.width() * sx;
	if( path_width > frame_rect.w )
	{
		sx *= frame_rect.w / path_width;
		sy *= frame_rect.w / path_width;
	}
	qreal path_height = path_rect.height() * sy;
	if( path_height > frame_rect.h )
	{
		sx *= frame_rect.h / path_height;
		sy *= frame_rect.h / path_height;
	}

	qreal dx = frame_rect.x;
	qreal dy = frame_rect.y;
	char halign = mlt_properties_get( filter_properties, "halign" )[0];
	switch( halign )
	{
		default:
		case 'l':
		case 'L':
			break;
		case 'c':
		case 'C':
			dx += ( frame_rect.w - ( sx * path_rect.width() ) ) / 2;
			break;
		case 'r':
		case 'R':
			dx += frame_rect.w - ( sx * path_rect.width() );
			break;
	}
	char valign = mlt_properties_get( filter_properties, "valign" )[0];
	switch( valign )
	{
		default:
		case 't':
		case 'T':
			break;
		case 'm':
		case 'M':
			dy += ( frame_rect.h - ( sy * path_rect.height() ) ) / 2;
			break;
		case 'b':
		case 'B':
			dy += frame_rect.h - ( sy * path_rect.height() );
			break;
	}

	QTransform transform;
	transform.translate( dx, dy );
	transform.scale( sx, sy );
	painter->setTransform( transform );
}

static void paint_background( QPainter* painter, QRectF path_rect, mlt_properties filter_properties )
{
	QColor bg_color = get_qcolor( filter_properties, "bgcolour" );
	painter->fillRect( path_rect, bg_color );
}

static void paint_text( QPainter* painter, QPainterPath* qpath, mlt_properties filter_properties )
{
	QPen pen = get_qpen( filter_properties );
	painter->setPen( pen );
	QBrush brush = get_qbrush( filter_properties );
	painter->setBrush( brush );
	painter->drawPath( *qpath );
}

static mlt_properties get_filter_properties( mlt_filter filter, mlt_frame frame )
{
	mlt_properties properties = mlt_frame_get_unique_properties( frame, MLT_FILTER_SERVICE(filter) );
	if ( !properties )
		properties = MLT_FILTER_PROPERTIES(filter);
	return properties;
}

static int filter_get_image( mlt_frame frame, uint8_t **image, mlt_image_format *image_format, int *width, int *height, int writable )
{
	int error = 0;
	mlt_filter filter = (mlt_filter)mlt_frame_pop_service( frame );
	char* argument = (char*)mlt_frame_pop_service( frame );
	mlt_properties filter_properties = get_filter_properties( filter, frame );
	mlt_profile profile = mlt_service_profile(MLT_FILTER_SERVICE(filter));
	mlt_position position = mlt_filter_get_position( filter, frame );
	mlt_position length = mlt_filter_get_length2( filter, frame );
	QString geom_str = QString::fromLatin1( mlt_properties_get( filter_properties, "geometry" ) );
	if( geom_str.isEmpty() )
	{
		mlt_log_warning( MLT_FILTER_SERVICE(filter), "geometry property not set\n" );
		mlt_frame_get_image( frame, image, image_format, width, height, writable );
		free( argument );
		return 1;
	}
	mlt_rect rect = mlt_properties_anim_get_rect( filter_properties, "geometry", position, length );

	// Get the current image
	*image_format = mlt_image_rgb24a;
	mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "resize_alpha", 255 );
	error = mlt_frame_get_image( frame, image, image_format, width, height, writable );

	if( !error )
	{
		if ( geom_str.contains('%') )
		{
			rect.x *= *width;
			rect.w *= *width;
			rect.y *= *height;
			rect.h *= *height;
		}

		QImage qimg( *width, *height, QImage::Format_ARGB32 );
		convert_mlt_to_qimage_rgba( *image, &qimg, *width, *height );

		QPainterPath text_path;
		QRectF path_rect = get_text_path( &text_path, filter_properties, argument );
		QPainter painter( &qimg );
		painter.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing );
		transform_painter( &painter, rect, path_rect, filter_properties, profile );
		paint_background( &painter, path_rect, filter_properties );
		paint_text( &painter, &text_path, filter_properties );
		painter.end();

		convert_qimage_to_mlt_rgba( &qimg, *image, *width, *height );
	}
	free( argument );

	return error;
}

/** Filter processing.
*/

static mlt_frame filter_process( mlt_filter filter, mlt_frame frame )
{
	mlt_properties properties = get_filter_properties( filter, frame );
	char* argument = mlt_properties_get( properties, "argument" );
	if ( !argument || !strcmp( "", argument ) )
		return frame;

	// Save the text to be used by get_image() to support parallel processing
	// when this filter is encapsulated by other filters.
	mlt_frame_push_service( frame, strdup( argument ) );

	// Push the filter on to the stack
	mlt_frame_push_service( frame, filter );

	// Push the get_image on to the stack
	mlt_frame_push_get_image( frame, filter_get_image );

	return frame;
}

/** Constructor for the filter.
*/

extern "C" {

mlt_filter filter_qtext_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
{
	mlt_filter filter = mlt_filter_new();

	if( !filter ) return NULL;

	if ( !createQApplicationIfNeeded( MLT_FILTER_SERVICE(filter) ) )  {
		mlt_filter_close( filter );
		return NULL;
	}

	filter->process = filter_process;

	mlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter );
	// Assign default values
	mlt_properties_set( filter_properties, "argument", arg ? arg: "text" );
	mlt_properties_set( filter_properties, "geometry", "0%/0%:100%x100%:100%" );
	mlt_properties_set( filter_properties, "family", "Sans" );
	mlt_properties_set( filter_properties, "size", "48" );
	mlt_properties_set( filter_properties, "weight", "400" );
	mlt_properties_set( filter_properties, "style", "normal" );
	mlt_properties_set( filter_properties, "fgcolour", "0x000000ff" );
	mlt_properties_set( filter_properties, "bgcolour", "0x00000020" );
	mlt_properties_set( filter_properties, "olcolour", "0x00000000" );
	mlt_properties_set( filter_properties, "pad", "0" );
	mlt_properties_set( filter_properties, "halign", "left" );
	mlt_properties_set( filter_properties, "valign", "top" );
	mlt_properties_set( filter_properties, "outline", "0" );
	mlt_properties_set_int( filter_properties, "_filter_private", 1 );

	return filter;
}

}
<commit_msg>Fix white flash on property changes.<commit_after>/*
 * filter_qtext.cpp -- text overlay filter
 * Copyright (c) 2018 Meltytech, LLC
 *
 * This 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
 */

#include "common.h"
#include <framework/mlt.h>
#include <framework/mlt_log.h>
#include <QPainter>
#include <QString>

static QRectF get_text_path( QPainterPath* qpath, mlt_properties filter_properties, const char* text )
{
	int outline = mlt_properties_get_int( filter_properties, "outline" );
	char halign = mlt_properties_get( filter_properties, "halign" )[0];
	char style = mlt_properties_get( filter_properties, "style" )[0];
	int pad = mlt_properties_get_int( filter_properties, "pad" );
	int offset = pad + ( outline / 2 );
	int width = 0;
	int height = 0;

	qpath->setFillRule( Qt::WindingFill );

	// Get the strings to display
	QString s = QString::fromUtf8(text);
	QStringList lines = s.split( "\n" );

	// Configure the font
	QFont font;
	font.setPixelSize( mlt_properties_get_int( filter_properties, "size" ) );
	font.setFamily( mlt_properties_get( filter_properties, "family" ) );
	font.setWeight( ( mlt_properties_get_int( filter_properties, "weight" ) / 10 ) -1 );
	switch( style )
	{
	case 'i':
	case 'I':
		font.setStyle( QFont::StyleItalic );
		break;
	}
	QFontMetrics fm( font );

	// Determine the text rectangle size
	height = fm.lineSpacing() * lines.size();
	for( int i = 0; i < lines.size(); ++i )
	{
		const QString line = lines[i];
		int line_width = fm.width(line);
		int bearing = (line.size() > 0) ? fm.leftBearing(line.at(0)) : 0;
		if (bearing < 0)
			line_width -= bearing;
		bearing = (line.size() > 0) ? fm.rightBearing(line.at(line.size() - 1)) : 0;
		if (bearing < 0)
			line_width -= bearing;
		if (line_width > width)
			width = line_width;
	}

	// Lay out the text in the path
	int x = 0;
	int y = fm.ascent() + offset;
	for( int i = 0; i < lines.size(); ++i )
	{
		QString line = lines.at(i);
		x = offset;
		int line_width = fm.width(line);
		int bearing = (line.size() > 0)? fm.leftBearing(line.at(0)) : 0;

		if (bearing < 0) {
			line_width -= bearing;
			x -= bearing;
		}
		bearing = (line.size() > 0)? fm.rightBearing(line.at(line.size() - 1)) : 0;
		if (bearing < 0)
			line_width -= bearing;

		switch( halign )
		{
			default:
			case 'l':
			case 'L':
				break;
			case 'c':
			case 'C':
				x += ( width - line_width ) / 2;
				break;
			case 'r':
			case 'R':
				x += width - line_width;
				break;
		}
		qpath->addText( x, y, font, line );
		y += fm.lineSpacing();
	}

	// Account for outline and pad
	width += offset * 2;
	height += offset * 2;
	// Sanity check
	if( width == 0 ) width = 1;
	height += 2; // I found some fonts whose descenders get cut off.

	return QRectF( 0, 0, width, height );
}

static QColor get_qcolor( mlt_properties filter_properties, const char* name )
{
	mlt_color color = mlt_properties_get_color( filter_properties, name );
	return QColor( color.r, color.g, color.b, color.a );
}

static QPen get_qpen( mlt_properties filter_properties )
{
	QColor color;
	int outline = mlt_properties_get_int( filter_properties, "outline" );
	QPen pen;

	pen.setWidth( outline );
	if( outline )
	{
		color = get_qcolor( filter_properties, "olcolour" );
	}
	else
	{
		color = get_qcolor( filter_properties, "bgcolour" );
	}
	pen.setColor( color );

	return pen;
}

static QBrush get_qbrush( mlt_properties filter_properties )
{
	QColor color = get_qcolor( filter_properties, "fgcolour" );
	return QBrush ( color );
}

static void transform_painter( QPainter* painter, mlt_rect frame_rect, QRectF path_rect, mlt_properties filter_properties, mlt_profile profile )
{
	qreal sx = 1.0;
	qreal sy = mlt_profile_sar( profile );
	qreal path_width = path_rect.width() * sx;
	if( path_width > frame_rect.w )
	{
		sx *= frame_rect.w / path_width;
		sy *= frame_rect.w / path_width;
	}
	qreal path_height = path_rect.height() * sy;
	if( path_height > frame_rect.h )
	{
		sx *= frame_rect.h / path_height;
		sy *= frame_rect.h / path_height;
	}

	qreal dx = frame_rect.x;
	qreal dy = frame_rect.y;
	char halign = mlt_properties_get( filter_properties, "halign" )[0];
	switch( halign )
	{
		default:
		case 'l':
		case 'L':
			break;
		case 'c':
		case 'C':
			dx += ( frame_rect.w - ( sx * path_rect.width() ) ) / 2;
			break;
		case 'r':
		case 'R':
			dx += frame_rect.w - ( sx * path_rect.width() );
			break;
	}
	char valign = mlt_properties_get( filter_properties, "valign" )[0];
	switch( valign )
	{
		default:
		case 't':
		case 'T':
			break;
		case 'm':
		case 'M':
			dy += ( frame_rect.h - ( sy * path_rect.height() ) ) / 2;
			break;
		case 'b':
		case 'B':
			dy += frame_rect.h - ( sy * path_rect.height() );
			break;
	}

	QTransform transform;
	transform.translate( dx, dy );
	transform.scale( sx, sy );
	painter->setTransform( transform );
}

static void paint_background( QPainter* painter, QRectF path_rect, mlt_properties filter_properties )
{
	QColor bg_color = get_qcolor( filter_properties, "bgcolour" );
	painter->fillRect( path_rect, bg_color );
}

static void paint_text( QPainter* painter, QPainterPath* qpath, mlt_properties filter_properties )
{
	QPen pen = get_qpen( filter_properties );
	painter->setPen( pen );
	QBrush brush = get_qbrush( filter_properties );
	painter->setBrush( brush );
	painter->drawPath( *qpath );
}

static mlt_properties get_filter_properties( mlt_filter filter, mlt_frame frame )
{
	mlt_properties properties = mlt_frame_get_unique_properties( frame, MLT_FILTER_SERVICE(filter) );
	if ( !properties )
		properties = MLT_FILTER_PROPERTIES(filter);
	return properties;
}

static int filter_get_image( mlt_frame frame, uint8_t **image, mlt_image_format *image_format, int *width, int *height, int writable )
{
	int error = 0;
	mlt_filter filter = (mlt_filter)mlt_frame_pop_service( frame );
	char* argument = (char*)mlt_frame_pop_service( frame );
	mlt_properties filter_properties = get_filter_properties( filter, frame );
	mlt_profile profile = mlt_service_profile(MLT_FILTER_SERVICE(filter));
	mlt_position position = mlt_filter_get_position( filter, frame );
	mlt_position length = mlt_filter_get_length2( filter, frame );
	QString geom_str = QString::fromLatin1( mlt_properties_get( filter_properties, "geometry" ) );
	if( geom_str.isEmpty() )
	{
		free( argument );
		mlt_log_warning( MLT_FILTER_SERVICE(filter), "geometry property not set\n" );
		return mlt_frame_get_image( frame, image, image_format, width, height, writable );
	}
	mlt_rect rect = mlt_properties_anim_get_rect( filter_properties, "geometry", position, length );

	// Get the current image
	*image_format = mlt_image_rgb24a;
	mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "resize_alpha", 255 );
	error = mlt_frame_get_image( frame, image, image_format, width, height, writable );

	if( !error )
	{
		if ( geom_str.contains('%') )
		{
			rect.x *= *width;
			rect.w *= *width;
			rect.y *= *height;
			rect.h *= *height;
		}

		QImage qimg( *width, *height, QImage::Format_ARGB32 );
		convert_mlt_to_qimage_rgba( *image, &qimg, *width, *height );

		QPainterPath text_path;
		QRectF path_rect = get_text_path( &text_path, filter_properties, argument );
		QPainter painter( &qimg );
		painter.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing );
		transform_painter( &painter, rect, path_rect, filter_properties, profile );
		paint_background( &painter, path_rect, filter_properties );
		paint_text( &painter, &text_path, filter_properties );
		painter.end();

		convert_qimage_to_mlt_rgba( &qimg, *image, *width, *height );
	}
	free( argument );

	return error;
}

/** Filter processing.
*/

static mlt_frame filter_process( mlt_filter filter, mlt_frame frame )
{
	mlt_properties properties = get_filter_properties( filter, frame );
	char* argument = mlt_properties_get( properties, "argument" );
	if ( !argument || !strcmp( "", argument ) )
		return frame;

	// Save the text to be used by get_image() to support parallel processing
	// when this filter is encapsulated by other filters.
	mlt_frame_push_service( frame, strdup( argument ) );

	// Push the filter on to the stack
	mlt_frame_push_service( frame, filter );

	// Push the get_image on to the stack
	mlt_frame_push_get_image( frame, filter_get_image );

	return frame;
}

/** Constructor for the filter.
*/

extern "C" {

mlt_filter filter_qtext_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
{
	mlt_filter filter = mlt_filter_new();

	if( !filter ) return NULL;

	if ( !createQApplicationIfNeeded( MLT_FILTER_SERVICE(filter) ) )  {
		mlt_filter_close( filter );
		return NULL;
	}

	filter->process = filter_process;

	mlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter );
	// Assign default values
	mlt_properties_set( filter_properties, "argument", arg ? arg: "text" );
	mlt_properties_set( filter_properties, "geometry", "0%/0%:100%x100%:100%" );
	mlt_properties_set( filter_properties, "family", "Sans" );
	mlt_properties_set( filter_properties, "size", "48" );
	mlt_properties_set( filter_properties, "weight", "400" );
	mlt_properties_set( filter_properties, "style", "normal" );
	mlt_properties_set( filter_properties, "fgcolour", "0x000000ff" );
	mlt_properties_set( filter_properties, "bgcolour", "0x00000020" );
	mlt_properties_set( filter_properties, "olcolour", "0x00000000" );
	mlt_properties_set( filter_properties, "pad", "0" );
	mlt_properties_set( filter_properties, "halign", "left" );
	mlt_properties_set( filter_properties, "valign", "top" );
	mlt_properties_set( filter_properties, "outline", "0" );
	mlt_properties_set_int( filter_properties, "_filter_private", 1 );

	return filter;
}

}
<|endoftext|>


<commit_before>#include "LnkdLst.h"
#include "CircularLL.h"
#include "DoublyLL.h"
#include "PriorityLL.h"
#include "SortedLL.h"
#include "Queue.h"
#include "Stack.h"

int main()
{
	//Linked List
	cout << "Linked List" << endl;
	cout << "=============" << endl;
	LnkdLst<float> list1(0);
	LnkdLst<float> list2(list1);

	list2.append(4);
	list2.append(8);
	list2.append(10);

	list1.append(3);
	list1.append(5);
	list1.prepend(2);
	list1.prepend(7);
	list1.extract(5);
	list1.extract(2);
	list1.insertAfter(3, 9);
	list1.insertAfter(0, 1);
	list1.insertBefore(7, 3);
	list1.insertBefore(1, 8);

	LnkdLst<float> list3(list1);

	cout << "This is list [1]" << endl;
	cout << "================" << endl;
	cout << "The first value is: " << list1.getHead() << endl;
	cout << "The last value is: " << list1.getTail() << endl;
	cout << list1.toString() << endl;

	cout << "This is list [2]" << endl;
	cout << "================" << endl;
	cout << "The first value is: " << list2.getHead() << endl;
	cout << "The last value is: " << list2.getTail() << endl;
	cout << list2.toString() << endl;

	cout << "Setting list[1] = list[2]" << endl;
	list1 = list2;
	cout << "================" << endl;
	cout << "The first value is: " << list1.getHead() << endl;
	cout << "The last value is: " << list1.getTail() << endl;
	cout << list1.toString() << endl;

	cout << "This is list [3]" << endl;
	cout << "================" << endl;
	cout << "The first value is: " << list3.getHead() << endl;
	cout << "The last value is: " << list3.getTail() << endl;
	cout << list3.toString() << endl;

	//Stack
	cout << "Stack" << endl;
	cout << "=============" << endl;
	Stack<float> stack(2);
	stack.push(4);
	stack.push(8);
	stack.toString();
	cout << "Stack top: " << stack.top() << endl;
	cout << "Stack size: " << stack.size() << endl;
	stack.pop();
	stack.pop();
        cout << "Pop twice" << endl;
	stack.toString();
	cout << "Final Stack size: " << stack.size() << endl;

	//Queue
	cout << "Queue" << endl;
	cout << "=============" << endl;
	Queue<float> queue(4);
	queue.enqueue(7);
	queue.enqueue(0);
	queue.toString();
        cout << "Make Queue empty" << endl;
	queue.makeEmpty();
	queue.enqueue(2);
        cout << "Final Queue Contents" << endl;
	queue.toString();

	//Doubly LL
	cout << "Doubly Linked List" << endl;
	cout << "=============" << endl;
	DoublyLL<float> doubly(8);
	doubly.prepend(4);
	doubly.prepend(0);
	doubly.append(7);
	doubly.append(9);
	doubly.extract(0);
	doubly.extract(1);
	doubly.insertBefore(9, 2);
	doubly.insertBefore(2, 3);
	doubly.insertAfter(4, 1);
	doubly.insertAfter(1, 5);
	doubly.toString();

	DoublyLL<float> doubly2(doubly);
	cout << "List 2" << endl;
	doubly2.toString();

	DoublyLL<float> doubly3(4);
	cout << "List 3" << endl;
	doubly3 = doubly2;
	doubly3.toString();

	//Circular LL
	cout << "Circular Linked List" << endl;
	cout << "=============" << endl;
	CircularLL<float> circList(8);
	circList.prepend(3);
	circList.append(2);
	circList.append(4);
	circList.extract(2);
	circList.insertBefore(8, 0);
	circList.insertAfter(4, 7);
	circList.toString();
	cout << "This is the tail: " << circList.getTail() << endl;

        cout << "Circular List 2" << endl;
	CircularLL<float> circList2(circList);
	circList2.toString();

	//Sorted LL
	cout << "Sorted Linked List" << endl;
	cout << "=============" << endl;
	SortedLL<float> sorted(4);
	sorted.insert(7);
	sorted.insert(5);
	sorted.insert(2);
	sorted.insert(4.5);
	sorted.insert(9);
	sorted.toString();

	cout << "Sorted List 2" << endl;
	SortedLL<float> sorted2(sorted);
	sorted2.insert(3);
	sorted2.toString();

	sorted = sorted2;
	sorted.toString();

	/*
	PriorityLL<float> priority(2);
	priority.appendP(8);
	priority.prependP(7);
	priority.extract(2);
	priority.toString(); */

	//To exit
	char c;
	cin >> c;

	return 0;
}
<commit_msg>added "==" for consistency<commit_after>#include "LnkdLst.h"
#include "CircularLL.h"
#include "DoublyLL.h"
#include "PriorityLL.h"
#include "SortedLL.h"
#include "Queue.h"
#include "Stack.h"

int main()
{
	//Linked List
	cout << "Linked List" << endl;
	cout << "=============" << endl;
	LnkdLst<float> list1(0);
	LnkdLst<float> list2(list1);

	list2.append(4);
	list2.append(8);
	list2.append(10);

	list1.append(3);
	list1.append(5);
	list1.prepend(2);
	list1.prepend(7);
	list1.extract(5);
	list1.extract(2);
	list1.insertAfter(3, 9);
	list1.insertAfter(0, 1);
	list1.insertBefore(7, 3);
	list1.insertBefore(1, 8);

	LnkdLst<float> list3(list1);

	cout << "This is list [1]" << endl;
	cout << "================" << endl;
	cout << "The first value is: " << list1.getHead() << endl;
	cout << "The last value is: " << list1.getTail() << endl;
	cout << list1.toString() << endl;

	cout << "This is list [2]" << endl;
	cout << "================" << endl;
	cout << "The first value is: " << list2.getHead() << endl;
	cout << "The last value is: " << list2.getTail() << endl;
	cout << list2.toString() << endl;

	cout << "Setting list[1] = list[2]" << endl;
	list1 = list2;
	cout << "================" << endl;
	cout << "The first value is: " << list1.getHead() << endl;
	cout << "The last value is: " << list1.getTail() << endl;
	cout << list1.toString() << endl;

	cout << "This is list [3]" << endl;
	cout << "================" << endl;
	cout << "The first value is: " << list3.getHead() << endl;
	cout << "The last value is: " << list3.getTail() << endl;
	cout << list3.toString() << endl;

	//Stack
	cout << "Stack" << endl;
	cout << "=============" << endl;
	Stack<float> stack(2);
	stack.push(4);
	stack.push(8);
	stack.toString();
	cout << "Stack top: " << stack.top() << endl;
	cout << "Stack size: " << stack.size() << endl;
	stack.pop();
	stack.pop();
        cout << "Pop twice" << endl;
	stack.toString();
	cout << "Final Stack size: " << stack.size() << endl;

	//Queue
	cout << "Queue" << endl;
	cout << "=============" << endl;
	Queue<float> queue(4);
	queue.enqueue(7);
	queue.enqueue(0);
	queue.toString();
        cout << "Make Queue empty" << endl;
	queue.makeEmpty();
	queue.enqueue(2);
        cout << "Final Queue Contents" << endl;
	queue.toString();

	//Doubly LL
	cout << "Doubly Linked List" << endl;
	cout << "=============" << endl;
	DoublyLL<float> doubly(8);
	doubly.prepend(4);
	doubly.prepend(0);
	doubly.append(7);
	doubly.append(9);
	doubly.extract(0);
	doubly.extract(1);
	doubly.insertBefore(9, 2);
	doubly.insertBefore(2, 3);
	doubly.insertAfter(4, 1);
	doubly.insertAfter(1, 5);
	doubly.toString();

	DoublyLL<float> doubly2(doubly);
	cout << "List 2" << endl;
	cout << "=============" << endl;
	doubly2.toString();

	DoublyLL<float> doubly3(4);
	cout << "List 3" << endl;
	cout << "=============" << endl;
	doubly3 = doubly2;
	doubly3.toString();

	//Circular LL
	cout << "Circular Linked List" << endl;
	cout << "=============" << endl;
	CircularLL<float> circList(8);
	circList.prepend(3);
	circList.append(2);
	circList.append(4);
	circList.extract(2);
	circList.insertBefore(8, 0);
	circList.insertAfter(4, 7);
	circList.toString();
	cout << "This is the tail: " << circList.getTail() << endl;

        cout << "Circular List 2" << endl;
        cout << "=============" << endl;
	CircularLL<float> circList2(circList);
	circList2.toString();

	//Sorted LL
	cout << "Sorted Linked List" << endl;
	cout << "=============" << endl;
	SortedLL<float> sorted(4);
	sorted.insert(7);
	sorted.insert(5);
	sorted.insert(2);
	sorted.insert(4.5);
	sorted.insert(9);
	sorted.toString();

	cout << "Sorted List 2" << endl;
	cout << "=============" << endl;
	SortedLL<float> sorted2(sorted);
	sorted2.insert(3);
	sorted2.toString();

	sorted = sorted2;
	sorted.toString();

	/*
	PriorityLL<float> priority(2);
	priority.appendP(8);
	priority.prependP(7);
	priority.extract(2);
	priority.toString(); */

	//To exit
	char c;
	cin >> c;

	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DffImpl.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hbrinkm $ $Date: 2006-11-01 09:14:29 $
 *
 *  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 "resources.hxx"

namespace doctok
{
class ShapeTypeToString
{
    typedef boost::shared_ptr<ShapeTypeToString> Pointer_t;

    static Pointer_t pInstance;

    typedef map<sal_uInt32, string> Map_t;
    Map_t mMap;

protected:
    ShapeTypeToString();

public:
    static Pointer_t Instance()
    {
        if (pInstance == NULL)
            pInstance = Pointer_t(new ShapeTypeToString());

        return pInstance;
    }

    string operator()(sal_uInt32 nShapeType)
    {
        return mMap[nShapeType];
    }
};

ShapeTypeToString::Pointer_t ShapeTypeToString::pInstance;

ShapeTypeToString::ShapeTypeToString()
{
    mMap[0]="NotPrimitive";
    mMap[1]="Rectangle";
    mMap[2]="RoundRectangle";
    mMap[3]="Ellipse";
    mMap[4]="Diamond";
    mMap[5]="IsocelesTriangle";
    mMap[6]="RightTriangle";
    mMap[7]="Parallelogram";
    mMap[8]="Trapezoid";
    mMap[9]="Hexagon";
    mMap[10]="Octagon";
    mMap[11]="Plus";
    mMap[12]="Star";
    mMap[13]="Arrow";
    mMap[14]="ThickArrow";
    mMap[15]="HomePlate";
    mMap[16]="Cube";
    mMap[17]="Balloon";
    mMap[18]="Seal";
    mMap[19]="Arc";
    mMap[20]="Line";
    mMap[21]="Plaque";
    mMap[22]="Can";
    mMap[23]="Donut";
    mMap[24]="TextSimple";
    mMap[25]="TextOctagon";
    mMap[26]="TextHexagon";
    mMap[27]="TextCurve";
    mMap[28]="TextWave";
    mMap[29]="TextRing";
    mMap[30]="TextOnCurve";
    mMap[31]="TextOnRing";
    mMap[32]="StraightConnector1";
    mMap[33]="BentConnector2";
    mMap[34]="BentConnector3";
    mMap[35]="BentConnector4";
    mMap[36]="BentConnector5";
    mMap[37]="CurvedConnector2";
    mMap[38]="CurvedConnector3";
    mMap[39]="CurvedConnector4";
    mMap[40]="CurvedConnector5";
    mMap[41]="Callout1";
    mMap[42]="Callout2";
    mMap[43]="Callout3";
    mMap[44]="AccentCallout1";
    mMap[45]="AccentCallout2";
    mMap[46]="AccentCallout3";
    mMap[47]="BorderCallout1";
    mMap[48]="BorderCallout2";
    mMap[49]="BorderCallout3";
    mMap[50]="AccentBorderCallout1";
    mMap[51]="AccentBorderCallout2";
    mMap[52]="AccentBorderCallout3";
    mMap[53]="Ribbon";
    mMap[54]="Ribbon2";
    mMap[55]="Chevron";
    mMap[56]="Pentagon";
    mMap[57]="NoSmoking";
    mMap[58]="Seal8";
    mMap[59]="Seal16";
    mMap[60]="Seal32";
    mMap[61]="WedgeRectCallout";
    mMap[62]="WedgeRRectCallout";
    mMap[63]="WedgeEllipseCallout";
    mMap[64]="Wave";
    mMap[65]="FoldedCorner";
    mMap[66]="LeftArrow";
    mMap[67]="DownArrow";
    mMap[68]="UpArrow";
    mMap[69]="LeftRightArrow";
    mMap[70]="UpDownArrow";
    mMap[71]="IrregularSeal1";
    mMap[72]="IrregularSeal2";
    mMap[73]="LightningBolt";
    mMap[74]="Heart";
    mMap[75]="PictureFrame";
    mMap[76]="QuadArrow";
    mMap[77]="LeftArrowCallout";
    mMap[78]="RightArrowCallout";
    mMap[79]="UpArrowCallout";
    mMap[80]="DownArrowCallout";
    mMap[81]="LeftRightArrowCallout";
    mMap[82]="UpDownArrowCallout";
    mMap[83]="QuadArrowCallout";
    mMap[84]="Bevel";
    mMap[85]="LeftBracket";
    mMap[86]="RightBracket";
    mMap[87]="LeftBrace";
    mMap[88]="RightBrace";
    mMap[89]="LeftUpArrow";
    mMap[90]="BentUpArrow";
    mMap[91]="BentArrow";
    mMap[92]="Seal24";
    mMap[93]="StripedRightArrow";
    mMap[94]="NotchedRightArrow";
    mMap[95]="BlockArc";
    mMap[96]="SmileyFace";
    mMap[97]="VerticalScroll";
    mMap[98]="HorizontalScroll";
    mMap[99]="CircularArrow";
    mMap[100]="NotchedCircularArrow";
    mMap[101]="UturnArrow";
    mMap[102]="CurvedRightArrow";
    mMap[103]="CurvedLeftArrow";
    mMap[104]="CurvedUpArrow";
    mMap[105]="CurvedDownArrow";
    mMap[106]="CloudCallout";
    mMap[107]="EllipseRibbon";
    mMap[108]="EllipseRibbon2";
    mMap[109]="FlowChartProcess";
    mMap[110]="FlowChartDecision";
    mMap[111]="FlowChartInputOutput";
    mMap[112]="FlowChartPredefinedProcess";
    mMap[113]="FlowChartInternalStorage";
    mMap[114]="FlowChartDocument";
    mMap[115]="FlowChartMultidocument";
    mMap[116]="FlowChartTerminator";
    mMap[117]="FlowChartPreparation";
    mMap[118]="FlowChartManualInput";
    mMap[119]="FlowChartManualOperation";
    mMap[120]="FlowChartConnector";
    mMap[121]="FlowChartPunchedCard";
    mMap[122]="FlowChartPunchedTape";
    mMap[123]="FlowChartSummingJunction";
    mMap[124]="FlowChartOr";
    mMap[125]="FlowChartCollate";
    mMap[126]="FlowChartSort";
    mMap[127]="FlowChartExtract";
    mMap[128]="FlowChartMerge";
    mMap[129]="FlowChartOfflineStorage";
    mMap[130]="FlowChartOnlineStorage";
    mMap[131]="FlowChartMagneticTape";
    mMap[132]="FlowChartMagneticDisk";
    mMap[133]="FlowChartMagneticDrum";
    mMap[134]="FlowChartDisplay";
    mMap[135]="FlowChartDelay";
    mMap[136]="TextPlainText";
    mMap[137]="TextStop";
    mMap[138]="TextTriangle";
    mMap[139]="TextTriangleInverted";
    mMap[140]="TextChevron";
    mMap[141]="TextChevronInverted";
    mMap[142]="TextRingInside";
    mMap[143]="TextRingOutside";
    mMap[144]="TextArchUpCurve";
    mMap[145]="TextArchDownCurve";
    mMap[146]="TextCircleCurve";
    mMap[147]="TextButtonCurve";
    mMap[148]="TextArchUpPour";
    mMap[149]="TextArchDownPour";
    mMap[150]="TextCirclePour";
    mMap[151]="TextButtonPour";
    mMap[152]="TextCurveUp";
    mMap[153]="TextCurveDown";
    mMap[154]="TextCascadeUp";
    mMap[155]="TextCascadeDown";
    mMap[156]="TextWave1";
    mMap[157]="TextWave2";
    mMap[158]="TextWave3";
    mMap[159]="TextWave4";
    mMap[160]="TextInflate";
    mMap[161]="TextDeflate";
    mMap[162]="TextInflateBottom";
    mMap[163]="TextDeflateBottom";
    mMap[164]="TextInflateTop";
    mMap[165]="TextDeflateTop";
    mMap[166]="TextDeflateInflate";
    mMap[167]="TextDeflateInflateDeflate";
    mMap[168]="TextFadeRight";
    mMap[169]="TextFadeLeft";
    mMap[170]="TextFadeUp";
    mMap[171]="TextFadeDown";
    mMap[172]="TextSlantUp";
    mMap[173]="TextSlantDown";
    mMap[174]="TextCanUp";
    mMap[175]="TextCanDown";
    mMap[176]="FlowChartAlternateProcess";
    mMap[177]="FlowChartOffpageConnector";
    mMap[178]="Callout90";
    mMap[179]="AccentCallout90";
    mMap[180]="BorderCallout90";
    mMap[181]="AccentBorderCallout90";
    mMap[182]="LeftRightUpArrow";
    mMap[183]="Sun";
    mMap[184]="Moon";
    mMap[185]="BracketPair";
    mMap[186]="BracePair";
    mMap[187]="Seal4";
    mMap[188]="DoubleWave";
    mMap[189]="ActionButtonBlank";
    mMap[190]="ActionButtonHome";
    mMap[191]="ActionButtonHelp";
    mMap[192]="ActionButtonInformation";
    mMap[193]="ActionButtonForwardNext";
    mMap[194]="ActionButtonBackPrevious";
    mMap[195]="ActionButtonEnd";
    mMap[196]="ActionButtonBeginning";
    mMap[197]="ActionButtonReturn";
    mMap[198]="ActionButtonDocument";
    mMap[199]="ActionButtonSound";
    mMap[200]="ActionButtonMovie";
    mMap[201]="HostControl";
    mMap[202]="TextBox";
}

// DffOPT

sal_uInt32 DffOPT::get_property_count()
{
    return getInstance();
}

doctok::Reference<Properties>::Pointer_t
DffOPT::get_property(sal_uInt32 nPos)
{
    WW8FOPTE * pTmp = new WW8FOPTE(this, 0x8 + nPos * WW8FOPTE::getSize());
    pTmp->setIndex(nPos);

    return doctok::Reference<Properties>::Pointer_t(pTmp);
}

sal_uInt32 DffOPT::get_extraoffset_count()
{
    return get_property_count();
}

sal_uInt32 DffOPT::get_extraoffset(sal_uInt32 pos)
{
    sal_uInt32 nResult;
    sal_uInt32 nCount = get_property_count();

    if (pos < nCount)
    {
        nResult = 0x8 + nCount * WW8FOPTE::getSize();

        for (sal_uInt32 n = 0; n < pos; ++n)
        {
            WW8FOPTE aFOPTE(this, 0x8 + n * WW8FOPTE::getSize());

            if (aFOPTE.get_fComplex())
            {
                sal_uInt32 nValue = aFOPTE.get_op();
                nResult += nValue;
            }
        }
    }
    else
        nResult = getCount();

    return nResult;
}

//DffDGG

sal_uInt32 DffDGG::get_fidcl_count()
{
    return (getCount() - 0x18) / WW8FIDCL::getSize();
}

doctok::Reference<Properties>::Pointer_t
DffDGG::get_fidcl(sal_uInt32 pos)
{
    return doctok::Reference<Properties>::Pointer_t
        (new WW8FIDCL(this, 0x18 + pos * WW8FIDCL::getSize()));
}

// DffBSE

rtl::OUString DffBSE::get_blipname()
{
    rtl::OUString sResult;
    WW8FBSE aFBSE(this, 0x8);

    if (aFBSE.get_cbName() > 0)
        sResult = getString(0x24, aFBSE.get_cbName());

    return sResult;
}

WW8BinaryObjReference::Pointer_t DffBSE::get_binary()
{
    return WW8BinaryObjReference::Pointer_t
        (new WW8BinaryObjReference(this, WW8FBSE::getSize() + 0x8,
                                   getCount() - WW8FBSE::getSize() - 0x8));
}

// WW8FOPTE
void WW8FOPTE::resolveNoAuto(Properties & rHandler)
{
    sal_uInt16 nId = get_pid() + 1;
    sal_uInt32 nOp = get_op();
    sal_uInt32 nMask = 2;

    while (isBooleanDffOpt(nId))
    {
        WW8Value::Pointer_t pVal = createValue(getDffOptName(nId));
        rHandler.attribute(NS_rtf::LN_shpname, *pVal);

        pVal = createValue((nOp & nMask) != 0);
        rHandler.attribute(NS_rtf::LN_shpvalue, *pVal);

        --nId;
        nMask = nMask << 1;
    }
}

// DffFSP

rtl::OUString DffFSP::get_shptypename()
{
    string aName = (*ShapeTypeToString::Instance())(get_shptype());

    return rtl::OUString::createFromAscii(aName.c_str());
}

}
<commit_msg>corrected offset for binary content of picture data<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DffImpl.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hbrinkm $ $Date: 2006-11-06 10:48:06 $
 *
 *  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 "resources.hxx"

namespace doctok
{
class ShapeTypeToString
{
    typedef boost::shared_ptr<ShapeTypeToString> Pointer_t;

    static Pointer_t pInstance;

    typedef map<sal_uInt32, string> Map_t;
    Map_t mMap;

protected:
    ShapeTypeToString();

public:
    static Pointer_t Instance()
    {
        if (pInstance == NULL)
            pInstance = Pointer_t(new ShapeTypeToString());

        return pInstance;
    }

    string operator()(sal_uInt32 nShapeType)
    {
        return mMap[nShapeType];
    }
};

ShapeTypeToString::Pointer_t ShapeTypeToString::pInstance;

ShapeTypeToString::ShapeTypeToString()
{
    mMap[0]="NotPrimitive";
    mMap[1]="Rectangle";
    mMap[2]="RoundRectangle";
    mMap[3]="Ellipse";
    mMap[4]="Diamond";
    mMap[5]="IsocelesTriangle";
    mMap[6]="RightTriangle";
    mMap[7]="Parallelogram";
    mMap[8]="Trapezoid";
    mMap[9]="Hexagon";
    mMap[10]="Octagon";
    mMap[11]="Plus";
    mMap[12]="Star";
    mMap[13]="Arrow";
    mMap[14]="ThickArrow";
    mMap[15]="HomePlate";
    mMap[16]="Cube";
    mMap[17]="Balloon";
    mMap[18]="Seal";
    mMap[19]="Arc";
    mMap[20]="Line";
    mMap[21]="Plaque";
    mMap[22]="Can";
    mMap[23]="Donut";
    mMap[24]="TextSimple";
    mMap[25]="TextOctagon";
    mMap[26]="TextHexagon";
    mMap[27]="TextCurve";
    mMap[28]="TextWave";
    mMap[29]="TextRing";
    mMap[30]="TextOnCurve";
    mMap[31]="TextOnRing";
    mMap[32]="StraightConnector1";
    mMap[33]="BentConnector2";
    mMap[34]="BentConnector3";
    mMap[35]="BentConnector4";
    mMap[36]="BentConnector5";
    mMap[37]="CurvedConnector2";
    mMap[38]="CurvedConnector3";
    mMap[39]="CurvedConnector4";
    mMap[40]="CurvedConnector5";
    mMap[41]="Callout1";
    mMap[42]="Callout2";
    mMap[43]="Callout3";
    mMap[44]="AccentCallout1";
    mMap[45]="AccentCallout2";
    mMap[46]="AccentCallout3";
    mMap[47]="BorderCallout1";
    mMap[48]="BorderCallout2";
    mMap[49]="BorderCallout3";
    mMap[50]="AccentBorderCallout1";
    mMap[51]="AccentBorderCallout2";
    mMap[52]="AccentBorderCallout3";
    mMap[53]="Ribbon";
    mMap[54]="Ribbon2";
    mMap[55]="Chevron";
    mMap[56]="Pentagon";
    mMap[57]="NoSmoking";
    mMap[58]="Seal8";
    mMap[59]="Seal16";
    mMap[60]="Seal32";
    mMap[61]="WedgeRectCallout";
    mMap[62]="WedgeRRectCallout";
    mMap[63]="WedgeEllipseCallout";
    mMap[64]="Wave";
    mMap[65]="FoldedCorner";
    mMap[66]="LeftArrow";
    mMap[67]="DownArrow";
    mMap[68]="UpArrow";
    mMap[69]="LeftRightArrow";
    mMap[70]="UpDownArrow";
    mMap[71]="IrregularSeal1";
    mMap[72]="IrregularSeal2";
    mMap[73]="LightningBolt";
    mMap[74]="Heart";
    mMap[75]="PictureFrame";
    mMap[76]="QuadArrow";
    mMap[77]="LeftArrowCallout";
    mMap[78]="RightArrowCallout";
    mMap[79]="UpArrowCallout";
    mMap[80]="DownArrowCallout";
    mMap[81]="LeftRightArrowCallout";
    mMap[82]="UpDownArrowCallout";
    mMap[83]="QuadArrowCallout";
    mMap[84]="Bevel";
    mMap[85]="LeftBracket";
    mMap[86]="RightBracket";
    mMap[87]="LeftBrace";
    mMap[88]="RightBrace";
    mMap[89]="LeftUpArrow";
    mMap[90]="BentUpArrow";
    mMap[91]="BentArrow";
    mMap[92]="Seal24";
    mMap[93]="StripedRightArrow";
    mMap[94]="NotchedRightArrow";
    mMap[95]="BlockArc";
    mMap[96]="SmileyFace";
    mMap[97]="VerticalScroll";
    mMap[98]="HorizontalScroll";
    mMap[99]="CircularArrow";
    mMap[100]="NotchedCircularArrow";
    mMap[101]="UturnArrow";
    mMap[102]="CurvedRightArrow";
    mMap[103]="CurvedLeftArrow";
    mMap[104]="CurvedUpArrow";
    mMap[105]="CurvedDownArrow";
    mMap[106]="CloudCallout";
    mMap[107]="EllipseRibbon";
    mMap[108]="EllipseRibbon2";
    mMap[109]="FlowChartProcess";
    mMap[110]="FlowChartDecision";
    mMap[111]="FlowChartInputOutput";
    mMap[112]="FlowChartPredefinedProcess";
    mMap[113]="FlowChartInternalStorage";
    mMap[114]="FlowChartDocument";
    mMap[115]="FlowChartMultidocument";
    mMap[116]="FlowChartTerminator";
    mMap[117]="FlowChartPreparation";
    mMap[118]="FlowChartManualInput";
    mMap[119]="FlowChartManualOperation";
    mMap[120]="FlowChartConnector";
    mMap[121]="FlowChartPunchedCard";
    mMap[122]="FlowChartPunchedTape";
    mMap[123]="FlowChartSummingJunction";
    mMap[124]="FlowChartOr";
    mMap[125]="FlowChartCollate";
    mMap[126]="FlowChartSort";
    mMap[127]="FlowChartExtract";
    mMap[128]="FlowChartMerge";
    mMap[129]="FlowChartOfflineStorage";
    mMap[130]="FlowChartOnlineStorage";
    mMap[131]="FlowChartMagneticTape";
    mMap[132]="FlowChartMagneticDisk";
    mMap[133]="FlowChartMagneticDrum";
    mMap[134]="FlowChartDisplay";
    mMap[135]="FlowChartDelay";
    mMap[136]="TextPlainText";
    mMap[137]="TextStop";
    mMap[138]="TextTriangle";
    mMap[139]="TextTriangleInverted";
    mMap[140]="TextChevron";
    mMap[141]="TextChevronInverted";
    mMap[142]="TextRingInside";
    mMap[143]="TextRingOutside";
    mMap[144]="TextArchUpCurve";
    mMap[145]="TextArchDownCurve";
    mMap[146]="TextCircleCurve";
    mMap[147]="TextButtonCurve";
    mMap[148]="TextArchUpPour";
    mMap[149]="TextArchDownPour";
    mMap[150]="TextCirclePour";
    mMap[151]="TextButtonPour";
    mMap[152]="TextCurveUp";
    mMap[153]="TextCurveDown";
    mMap[154]="TextCascadeUp";
    mMap[155]="TextCascadeDown";
    mMap[156]="TextWave1";
    mMap[157]="TextWave2";
    mMap[158]="TextWave3";
    mMap[159]="TextWave4";
    mMap[160]="TextInflate";
    mMap[161]="TextDeflate";
    mMap[162]="TextInflateBottom";
    mMap[163]="TextDeflateBottom";
    mMap[164]="TextInflateTop";
    mMap[165]="TextDeflateTop";
    mMap[166]="TextDeflateInflate";
    mMap[167]="TextDeflateInflateDeflate";
    mMap[168]="TextFadeRight";
    mMap[169]="TextFadeLeft";
    mMap[170]="TextFadeUp";
    mMap[171]="TextFadeDown";
    mMap[172]="TextSlantUp";
    mMap[173]="TextSlantDown";
    mMap[174]="TextCanUp";
    mMap[175]="TextCanDown";
    mMap[176]="FlowChartAlternateProcess";
    mMap[177]="FlowChartOffpageConnector";
    mMap[178]="Callout90";
    mMap[179]="AccentCallout90";
    mMap[180]="BorderCallout90";
    mMap[181]="AccentBorderCallout90";
    mMap[182]="LeftRightUpArrow";
    mMap[183]="Sun";
    mMap[184]="Moon";
    mMap[185]="BracketPair";
    mMap[186]="BracePair";
    mMap[187]="Seal4";
    mMap[188]="DoubleWave";
    mMap[189]="ActionButtonBlank";
    mMap[190]="ActionButtonHome";
    mMap[191]="ActionButtonHelp";
    mMap[192]="ActionButtonInformation";
    mMap[193]="ActionButtonForwardNext";
    mMap[194]="ActionButtonBackPrevious";
    mMap[195]="ActionButtonEnd";
    mMap[196]="ActionButtonBeginning";
    mMap[197]="ActionButtonReturn";
    mMap[198]="ActionButtonDocument";
    mMap[199]="ActionButtonSound";
    mMap[200]="ActionButtonMovie";
    mMap[201]="HostControl";
    mMap[202]="TextBox";
}

// DffOPT

sal_uInt32 DffOPT::get_property_count()
{
    return getInstance();
}

doctok::Reference<Properties>::Pointer_t
DffOPT::get_property(sal_uInt32 nPos)
{
    WW8FOPTE * pTmp = new WW8FOPTE(this, 0x8 + nPos * WW8FOPTE::getSize());
    pTmp->setIndex(nPos);

    return doctok::Reference<Properties>::Pointer_t(pTmp);
}

sal_uInt32 DffOPT::get_extraoffset_count()
{
    return get_property_count();
}

sal_uInt32 DffOPT::get_extraoffset(sal_uInt32 pos)
{
    sal_uInt32 nResult;
    sal_uInt32 nCount = get_property_count();

    if (pos < nCount)
    {
        nResult = 0x8 + nCount * WW8FOPTE::getSize();

        for (sal_uInt32 n = 0; n < pos; ++n)
        {
            WW8FOPTE aFOPTE(this, 0x8 + n * WW8FOPTE::getSize());

            if (aFOPTE.get_fComplex())
            {
                sal_uInt32 nValue = aFOPTE.get_op();
                nResult += nValue;
            }
        }
    }
    else
        nResult = getCount();

    return nResult;
}

//DffDGG

sal_uInt32 DffDGG::get_fidcl_count()
{
    return (getCount() - 0x18) / WW8FIDCL::getSize();
}

doctok::Reference<Properties>::Pointer_t
DffDGG::get_fidcl(sal_uInt32 pos)
{
    return doctok::Reference<Properties>::Pointer_t
        (new WW8FIDCL(this, 0x18 + pos * WW8FIDCL::getSize()));
}

// DffBSE

rtl::OUString DffBSE::get_blipname()
{
    rtl::OUString sResult;
    WW8FBSE aFBSE(this, 0x8);

    if (aFBSE.get_cbName() > 0)
        sResult = getString(0x24, aFBSE.get_cbName());

    return sResult;
}

WW8BinaryObjReference::Pointer_t DffBSE::get_binary()
{
    WW8BinaryObjReference::Pointer_t pResult;

    if (getCount() > 0x45)
        pResult = WW8BinaryObjReference::Pointer_t
            (new WW8BinaryObjReference(this, 0x45,
                                       getCount() - 0x45));

    return pResult;
}

// WW8FOPTE
void WW8FOPTE::resolveNoAuto(Properties & rHandler)
{
    sal_uInt16 nId = get_pid() + 1;
    sal_uInt32 nOp = get_op();
    sal_uInt32 nMask = 2;

    while (isBooleanDffOpt(nId))
    {
        WW8Value::Pointer_t pVal = createValue(getDffOptName(nId));
        rHandler.attribute(NS_rtf::LN_shpname, *pVal);

        pVal = createValue((nOp & nMask) != 0);
        rHandler.attribute(NS_rtf::LN_shpvalue, *pVal);

        --nId;
        nMask = nMask << 1;
    }
}

// DffFSP

rtl::OUString DffFSP::get_shptypename()
{
    string aName = (*ShapeTypeToString::Instance())(get_shptype());

    return rtl::OUString::createFromAscii(aName.c_str());
}

}
<|endoftext|>


<commit_before>#include "fastlib/fastlib.h"
#include "../fastica/lin_alg.h"

void SaveCorrectly(const char *filename, Matrix a) {
  Matrix a_transpose;
  la::TransposeInit(a, &a_transpose);
  data::Save(filename, a_transpose);
}

int compare_doubles_ascending(const void* a, const void* b) {
  double* arg1 = (double*) a;
  double* arg2 = (double*) b;
  if(*arg1 < *arg2) {
    return -1;
  }
  else if(*arg1 == *arg2) {
    return 0;
  }
  else {
    return 1;
  }
}

double vasicekm(Vector v, index_t m) {

  Vector sorted_v;

  index_t n = v.length();

  sorted_v.Copy(v);

  qsort(sorted_v.ptr(), n, sizeof(double), compare_doubles_ascending);

  double sum_logs = 0;

  for(index_t i = 0; i < n; i++) {
    if((i + m) > (n - 1)) {
      sum_logs = sum_logs + log(sorted_v[n - 1] - sorted_v[i - m]);
    }
    else if((i - m) < 0) {
      sum_logs = sum_logs + log(sorted_v[i + m] - sorted_v[0]);
    }
    else {
      sum_logs = sum_logs + log(sorted_v[i + m] - sorted_v[i - m]);
    }
  }

  double h = (sum_logs / n) + log(n / (2 * m));

  return h;

}

void RADICALOptTheta(Matrix X_t, double std_dev, index_t m,
		     index_t reps, double new_k, double range,
		     double *theta_star, Matrix* rotator_star) {
  Matrix X_aug_t;

  index_t d = X_t.n_cols();
  index_t n = X_t.n_rows();

  if(reps == 1) {
    X_aug_t.Alias(X_t);
  }
  else {
    Matrix noise_matrix;
    Scale(std_dev,
	  RandNormalInit(n * reps, d, &noise_matrix));

    X_aug_t.Init(n * reps, d);

    double* X_t_elements = X_t.ptr();
    double* X_aug_t_elements = X_aug_t.ptr();

    index_t num_elements = d * n;
    for(index_t rep_num = 0; rep_num < reps; rep_num++) {
      memcpy(X_aug_t_elements + (rep_num * num_elements) * sizeof(double),
	     X_t_elements,
	     num_elements * sizeof(double));
    }

    la::AddTo(noise_matrix, &X_aug_t);
  }

  double perc = range / (M_PI / 2);
  double number_k = perc * k;
  index_t start  = (index_t) floor((k - number_k) / 2) + 1;
  index_t end_point = (index_t) ceil((k - number_k) / 2);

  for(index_t i = 0; i < k; i++) {
    double theta =
      ((double) (i - 1) / (double) (k - 1) * M_PI / 2) - (M_PI / 4);

    double cos_theta = cos(theta);
    double sin_theta = sin(theta);
    Matrix rotator;
    rotator.Init(2,2);
    rotator.set(0,0, cos_theta);
    rotator.set(0,1, sin_theta);
    rotator.set(1,0, -sin_theta);
    rotator.set(1,1, cos_theta);
    Matrix rotated_X_aug_t;
    la::MulTransBInit(X_aug_t, rotator, &rotated_X_aug_t);

    Vector marginal_at_theta;
    marginal_at_theta.Init(d);
    for(index_t j = 0; j < d; j++) {
      Vector col_vector;
      rotated_X_aug_t.MakeColumnVector(j, &col_vector);
      marginal_at_theta[j] = vasicekm(col_vector, m);
    }

}

void RADICAL(Matrix X, Matrix whitening_matrix, Matrix X_whitened,
	     index_t k, bool aug_flag, index_t reps, double std_dev, index_t m,
	     Matrix* W, Matrix* Y) {

  index_t d = X.n_rows();
  index_t n = X.n_cols();

  Matrix X_t, X_current_t, X_whitened_t;
  la::TransposeInit(X, &X_t);
  la::TransposeInit(X_whitened, &X_current_t);
  X_whitened_t.Copy(X_current_t);

  index_t sweeps = d - 1;
  Matrix* old_total_rotator;
  Matrix* total_rotator;
  Matrix* temp_total_rotator;
  DiagMatrixInit(d, 1, old_total_rotator);
  DiagMatrixInit(d, 1, total_rotator);

  index_t sweep_iteration = 0;

  index_t final_k = k;
  double start_k_float = final_k / pow(1.3, ceil(sweeps / 2));
  double new_k_float = start_k_float;

  for(index_t sweep_num = 1; sweep_num < sweeps; sweep_num++) {
    printf("Sweep # %d of %d.\n", sweep_num, sweeps);
    double range = M_PI / 2;

    double new_k;
    if(sweep_num > ((double) sweeps / 2)) {
      new_k_float *= 1.3;
      new_k = floor(new_k_float);
    }
    else {
      new_k_float = start_k_float;
      new_k = max(30, (int) floor(new_k_float));
    }

    for(index_t i = 0; i < d - 1; i++) {
      for(index_t j = i + 1; j < d; j++) {
	Matrix cur_subspace_t;
	Vector selected_columns;
	selected_columns.Init(2);
	selected_columns[0] = i;
	selected_columns[1] = j;
	MakeSubMatrixByColumns(selected_columns, X_current_t, &cur_subspace_t);

	double theta_star;
	Matrix rotator_star;
	RADICALOptTheta(cur_subspace_t, std_dev, m, reps, new_k, range,
			&theta_star, &rotator_star);

	Matrix new_rotator;
	DiagMatrixInit(d, 1, &new_rotator);

	new_rotator.set(i, i, cos(theta_star));
	new_rotator.set(i, j, -sin(theta_star));
	new_rotator.set(j, i, sin(theta_star));
	new_rotator.set(j, j, cos(theta_star));

	temp_total_rotator = old_total_rotator;
	old_total_rotator = total_rotator;
	total_rotator = temp_total_rotator;
	la::MulInit(new_rotator, *old_total_rotator, total_rotator);

	la::MulTransAOverwrite(X_whitened_t, *total_rotator, &X_current_t);
      }
    }
  }

  la::MulInit(*total_rotator, whitening_matrix, W);
  la::MulInit(*W, X, Y);
}

// there should be some way to wrap X, W, and Y into our module no? ask ryan

int RADICALMain(datanode *module, Matrix X, Matrix *W, Matrix *Y) {

  Matrix X_centered, X_whitened, whitening_matrix;

  index_t k = 150;
  bool aug_flag = false;
  index_t reps = 30;
  double std_dev = 0.175;

  index_t m = (index_t) floor(sqrt(n));

  Center(X, &X_centered);
  WhitenUsingSVD(X_centered, &X_whitened, &whitening_matrix);

  RADICAL(X, whitening_matrix, X_whitened,
	  k, aug_flag, reps, std_dev, m,
	  W, Y);

  return SUCCESS_PASS;
}

int main(int argc, char *argv[]) {
  fx_init(argc, argv);

  srand48(time(0));

  Matrix X, W, Y;

  const char *data = fx_param_str_req(NULL, "data");
  data::Load(data, &X);

  int ret_val = RADICALMain(fx_root, X, &W, &Y);

  //SaveCorrectly("unmixing_matrix.dat", W);
  //SaveCorrectly("indep_comps.dat", Y);

  fx_done();

  return ret_val;
}
<commit_msg>updated niche/radical<commit_after>#include "fastlib/fastlib.h"
#include "../fastica/lin_alg.h"

void SaveCorrectly(const char *filename, Matrix a) {
  Matrix a_transpose;
  la::TransposeInit(a, &a_transpose);
  data::Save(filename, a_transpose);
}

int compare_doubles_ascending(const void* a, const void* b) {
  double* arg1 = (double*) a;
  double* arg2 = (double*) b;
  if(*arg1 < *arg2) {
    return -1;
  }
  else if(*arg1 == *arg2) {
    return 0;
  }
  else {
    return 1;
  }
}

double vasicekm(Vector v, index_t m) {

  Vector sorted_v;

  index_t n = v.length();

  sorted_v.Copy(v);

  qsort(sorted_v.ptr(), n, sizeof(double), compare_doubles_ascending);

  double sum_logs = 0;

  for(index_t i = 0; i < n; i++) {
    if((i + m) > (n - 1)) {
      sum_logs = sum_logs + log(sorted_v[n - 1] - sorted_v[i - m]);
    }
    else if((i - m) < 0) {
      sum_logs = sum_logs + log(sorted_v[i + m] - sorted_v[0]);
    }
    else {
      sum_logs = sum_logs + log(sorted_v[i + m] - sorted_v[i - m]);
    }
  }

  double h = (sum_logs / n) + log(n / (2 * m));

  return h;

}

void RADICALOptTheta(Matrix X_t, double std_dev, index_t m,
		     index_t reps, double k, double range,
		     double *theta_star, Matrix* rotator_star) {
  Matrix X_aug_t;

  index_t d = X_t.n_cols();
  index_t n = X_t.n_rows();

  if(reps == 1) {
    X_aug_t.Alias(X_t);
  }
  else {
    Matrix noise_matrix;
    Scale(std_dev,
	  RandNormalInit(n * reps, d, &noise_matrix));

    X_aug_t.Init(n * reps, d);

    double* X_t_elements = X_t.ptr();
    double* X_aug_t_elements = X_aug_t.ptr();

    index_t num_elements = d * n;
    for(index_t rep_num = 0; rep_num < reps; rep_num++) {
      memcpy(X_aug_t_elements + (rep_num * num_elements) * sizeof(double),
	     X_t_elements,
	     num_elements * sizeof(double));
    }

    la::AddTo(noise_matrix, &X_aug_t);
  }

  Vector entropy;
  entropy.Init((index_t) k);

  for(index_t i = 0; i < k; i++) {
    double theta =
      ((double) (i - 1) / (k - 1) * M_PI / 2) - (M_PI / 4);

    double cos_theta = cos(theta);
    double sin_theta = sin(theta);
    Matrix rotator;
    rotator.Init(2,2);
    rotator.set(0,0, cos_theta);
    rotator.set(0,1, -sin_theta);
    rotator.set(1,0, sin_theta);
    rotator.set(1,1, cos_theta);
    Matrix rotated_X_aug_t;
    la::MulTransBInit(X_aug_t, rotator, &rotated_X_aug_t);

    Vector marginal_at_theta;
    marginal_at_theta.Init(d);
    for(index_t j = 0; j < d; j++) {
      Vector col_vector;
      rotated_X_aug_t.MakeColumnVector(j, &col_vector);
      marginal_at_theta[j] = vasicekm(col_vector, m);
    }

    entropy[i] = Sum(&marginal_at_theta);
  }

  double min_entropy = DBL_MAX;
  index_t arg_min_entropy = 0;

  for(index_t i = 0; i < k; i++) {
    if(entropy[i] < min_entropy) {
      arg_min_entropy = i;
      min_entropy = entropy[i];
    }
  }

  *theta_star = ((arg_min_entropy - 1) / (k - 1) * M_PI / 2) - (M_PI / 4);

  printf("rotated %5.2f degrees.\n", (*theta_star) / (2 * M_PI) * 360);

  rotator_star -> Init(2, 2);

  double cos_theta_star = cos(*theta_star);
  double sin_theta_star = sin(*theta_star);
  rotator_star -> set(0, 0, cos_theta_star);
  rotator_star -> set(0, 1, -sin_theta_star);
  rotator_star -> set(1, 0, sin_theta_star);
  rotator_star -> set(1, 1, cos_theta_star);

}

  void RADICAL(Matrix X, Matrix whitening_matrix, Matrix X_whitened,
	       index_t k, bool aug_flag, index_t reps, double std_dev, index_t m,
	       Matrix* W, Matrix* Y) {

  index_t d = X.n_rows();
  //  index_t n = X.n_cols();

  Matrix X_t, X_current_t, X_whitened_t;
  la::TransposeInit(X, &X_t);
  la::TransposeInit(X_whitened, &X_current_t);
  X_whitened_t.Copy(X_current_t);

  index_t sweeps = d - 1;
  Matrix* old_total_rotator = NULL;
  Matrix* total_rotator = NULL;
  Matrix* temp_total_rotator = NULL;
  DiagMatrixInit(d, 1, old_total_rotator);
  DiagMatrixInit(d, 1, total_rotator);

  index_t final_k = k;
  double start_k_float = final_k / pow(1.3, ceil(sweeps / 2));
  double new_k_float = start_k_float;

  for(index_t sweep_num = 1; sweep_num < sweeps; sweep_num++) {
    printf("Sweep # %d of %d.\n", sweep_num, sweeps);
    double range = M_PI / 2;

    double new_k;
    if(sweep_num > ((double) sweeps / 2)) {
      new_k_float *= 1.3;
      new_k = floor(new_k_float);
    }
    else {
      new_k_float = start_k_float;
      new_k = max(30, (int) floor(new_k_float));
    }

    for(index_t i = 0; i < d - 1; i++) {
      for(index_t j = i + 1; j < d; j++) {
	Matrix cur_subspace_t;
	Vector selected_columns;
	selected_columns.Init(2);
	selected_columns[0] = i;
	selected_columns[1] = j;
	MakeSubMatrixByColumns(selected_columns, X_current_t, &cur_subspace_t);

	double theta_star;
	Matrix rotator_star;
	RADICALOptTheta(cur_subspace_t, std_dev, m, reps, new_k, range,
			&theta_star, &rotator_star);

	Matrix new_rotator;
	DiagMatrixInit(d, 1, &new_rotator);

	new_rotator.set(i, i, cos(theta_star));
	new_rotator.set(i, j, -sin(theta_star));
	new_rotator.set(j, i, sin(theta_star));
	new_rotator.set(j, j, cos(theta_star));

	temp_total_rotator = old_total_rotator;
	old_total_rotator = total_rotator;
	total_rotator = temp_total_rotator;
	la::MulInit(new_rotator, *old_total_rotator, total_rotator);

	la::MulTransAOverwrite(X_whitened_t, *total_rotator, &X_current_t);
      }
    }
  }

  la::MulInit(*total_rotator, whitening_matrix, W);
  la::MulInit(*W, X, Y);
}

// there should be some way to wrap X, W, and Y into our module no? ask ryan

int RADICALMain(datanode *module, Matrix X, Matrix *W, Matrix *Y) {

  Matrix X_centered, X_whitened, whitening_matrix;

  index_t n = X.n_cols();

  index_t k = 150;
  bool aug_flag = false;
  index_t reps = 30;
  double std_dev = 0.175;

  index_t m = (index_t) floor(sqrt(n));

  Center(X, &X_centered);
  WhitenUsingSVD(X_centered, &X_whitened, &whitening_matrix);

  RADICAL(X, whitening_matrix, X_whitened,
	  k, aug_flag, reps, std_dev, m,
	  W, Y);

  return SUCCESS_PASS;
}

int main(int argc, char *argv[]) {
  fx_init(argc, argv);

  srand48(time(0));

  Matrix X, W, Y;

  const char *data = fx_param_str_req(NULL, "data");
  data::Load(data, &X);

  int ret_val = RADICALMain(fx_root, X, &W, &Y);

  //SaveCorrectly("unmixing_matrix.dat", W);
  //SaveCorrectly("indep_comps.dat", Y);

  fx_done();

  return ret_val;
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkVTKImageIO.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.

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

=========================================================================*/
#include "itkVTKImageIO.h"
#include <stdio.h>

namespace itk
{

VTKImageIO::VTKImageIO()
{
  this->SetNumberOfDimensions(2);
  m_ByteOrder = LittleEndian;
  m_FileType = ASCII;

}

VTKImageIO::~VTKImageIO()
{
}

bool VTKImageIO::OpenVTKFileForReading(std::ifstream& os,
                                       const char* filename)

{
  // Make sure that we have a file to
  if ( filename == "" )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    return false;
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for reading
  itkDebugMacro(<< "Initialize: opening file " << filename);

  // Actually open the file
  int openMode = std::ios::in;

#ifdef _WIN32
  openMode |= std::ios::binary;
#endif
#if defined(__GNUC__) && __GNUC__ >= 3
  os.open(filename, static_cast<std::ios_base::openmode>(openMode));
#else
  os.open(filename, openMode);
#endif
  if ( os.fail() )
    {
    itkExceptionMacro(<< "Could not open file for reading: " << filename);
    return false;
    }

  return true;
}

bool VTKImageIO::OpenVTKFileForWriting(std::ofstream& os,
                                       const char* filename)

{
  // Make sure that we have a file to
  if ( filename == "" )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    return false;
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for writing
  itkDebugMacro(<< "Initialize: opening file " << filename);

  // Actually open the file
  int openMode = std::ios::out;

#ifdef _WIN32
  openMode |= std::ios::binary;
#endif
#if defined(__GNUC__) && __GNUC__ >= 3
  os.open(filename, static_cast<std::ios_base::openmode>(openMode));
#else
  os.open(filename, openMode);
#endif
  if ( os.fail() )
    {
    itkExceptionMacro(<< "Could not open file for writing: " << filename);
    return false;
    }

  return true;
}

bool VTKImageIO::CanReadFile(const char* filename)
{
  std::ifstream file;
  char buffer[256];
  std::string fname(filename);

  if ( fname.find(".vtk") >= fname.length() )
    {
    return false;
    }

  if ( ! this->OpenVTKFileForReading(file, filename) )
    {
    return false;
    }

  // Check to see if its a vtk structured points file
  file.getline(buffer,255);
  file.getline(buffer,255);
  file.getline(buffer,255);
  file.getline(buffer,255);

  fname = buffer;

  if ( fname.find("STRUCTURED_POINTS") < fname.length() ||
       fname.find("structured_points") < fname.length() )
    {
    return true;
    }
  else
    {
    return false;
    }
}

void VTKImageIO::Read(void* buffer)
{
  std::ifstream file;
  char line[255];
  std::string text;

  // Check the input
  //
  if ( ! this->OpenVTKFileForReading(file, m_FileName.c_str()) )
    {
    itkExceptionMacro(<< "Cannot read requested file");
    }

  file.getline(line,255);
  file.getline(line,255);
  file.getline(line,255);
  text = line;
  if ( text.find("ASCII") < text.length() ||
       text.find("ascii") < text.length() )
    {
    this->SetFileTypeToASCII();
    }
  else if ( text.find("BINARY") < text.length() ||
            text.find("binary") < text.length() )
    {
    this->SetFileTypeToBinary();
    }
  else
    {
    itkExceptionMacro(<< "Unrecognized type");
    }
  file.getline(line,255);
  text = line;
  if ( text.find("STRUCTURED_POINTS") >= text.length() &&
       text.find("structured_points") >= text.length() )
    {
    itkExceptionMacro(<< "Not structured points, can't read");
    }

  //extract dimensions, spacing, origin
  unsigned int dims[3];
  float spacing[3];
  float origin[3];
  file.getline(line,255);
  text = line;
  int i;

  if ( text.find("DIMENSIONS") < text.length() ||
       text.find("dimensions") < text.length() )
    {
    sscanf(line, "%*s %d %d %d", dims, dims+1, dims+2);
    if ( dims[2] <= 1 )
      {
      this->SetNumberOfDimensions(2);
      }
    else
      {
      this->SetNumberOfDimensions(3);
      }
    for ( i=0; i < m_NumberOfDimensions; i++ )
      {
      m_Dimensions[i] = dims[i];
      }
    }
  else
    {
    itkExceptionMacro(<<"No dimensions defined");
    }

  file.getline(line,255);
  text = line;
  if ( text.find("SPACING") < text.length() ||
       text.find("spacing") < text.length() )
    {
    sscanf(line, "%*s %f %f %f", spacing, spacing+1, spacing+2);
    for ( i=0; i < m_NumberOfDimensions; i++ )
      {
      m_Spacing[i] = spacing[i];
      }
    }
  else
    {
    itkExceptionMacro(<<"No spacing defined");
    }

  file.getline(line,255);
  text = line;
  if ( text.find("ORIGIN") < text.length() ||
       text.find("origin") < text.length() )
    {
    sscanf(line, "%*s %f %f %f", origin, origin+1, origin+2);
    for ( i=0; i < m_NumberOfDimensions; i++ )
      {
      m_Origin[i] = origin[i];
      }
    }
  else
    {
    itkExceptionMacro(<<"No origin defined");
    }

  //Now grab the data; need to determine the pixel type
  file.getline(line,255);
  text = line;
  while ( text.find("SCALARS") >= text.length() ||
          text.find("scalars") >= text.length() )
    {
    file.getline(line,255);
    text = line;
    }
  char pixelType[256];
  sscanf(line, "%*s %*s %s", pixelType);
  text = pixelType;
  if ( text.find("float") < text.length() )
    {
    SetPixelType(FLOAT);
    SetComponentType(FLOAT);
    }
  else if ( text.find("double") < text.length() )
    {
    SetPixelType(DOUBLE);
    SetComponentType(DOUBLE);
    }
  else if ( text.find("unsigned_char") < text.length() )
    {
    SetPixelType(UCHAR);
    SetComponentType(UCHAR);
    }
  else if ( text.find("char") < text.length() )
    {
    SetPixelType(CHAR);
    SetComponentType(CHAR);
    }
  else if ( text.find("unsigned_short") < text.length() )
    {
    SetPixelType(USHORT);
    SetComponentType(USHORT);
    }
  else if ( text.find("short") < text.length() )
    {
    SetPixelType(SHORT);
    SetComponentType(SHORT);
    }
  else if ( text.find("unsigned_int") < text.length() )
    {
    SetPixelType(UINT);
    SetComponentType(UINT);
    }
  else if ( text.find("int") < text.length() )
    {
    SetPixelType(INT);
    SetComponentType(INT);
    }
  else if ( text.find("unsigned_long") < text.length() )
    {
    SetPixelType(ULONG);
    SetComponentType(ULONG);
    }
  else if ( text.find("long") < text.length() )
    {
    SetPixelType(LONG);
    SetComponentType(LONG);
    }
  else
    {
    itkExceptionMacro(<<"Unrecognized type");
    }

  // grab the trailing lookup table line
  file.getline(line,255);
  //We are positioned at the data. The data is read depending on whether
  //it is ASCII or binary.
  if ( m_FileType == ASCII )
    {
    this->ReadBufferAsASCII(file, buffer, this->GetComponentType(),
                            this->GetImageSizeInComponents());
    }
  else
    {
    file.read(static_cast<char*>(buffer), this->GetImageSizeInBytes());
    }
}

void VTKImageIO::ReadImageInformation()
{
}

bool VTKImageIO::CanWriteFile(const char*)
{
  if ( m_FileName != "" &&
       m_FileName.find(".vtk") < m_FileName.length() )
    {
    return true;
    }
  return false;
}

void VTKImageIO::Write(void* buffer)
{
  std::ofstream file;
  if ( ! this->OpenVTKFileForWriting(file,m_FileName.c_str()) )
    {
    return;
    }

  // Check the image region for proper dimensions, etc.
  unsigned int numDims = this->GetNumberOfDimensions();
  if ( numDims < 2 || numDims > 3 )
    {
    itkExceptionMacro(<<"VTK Writer can only write 2 or 3-dimensional images");
    return;
    }
  ImageIORegion ioRegion = this->GetIORegion();

  // Write the VTK header information
  file << "# vtk DataFile Version 3.0\n";
  file << "VTK File Generated by Insight Segmentation and Registration Toolkit (ITK)\n";

  if ( this->GetFileType() == ASCII ) { file << "ASCII\n"; }
  else { file << "BINARY\n"; }

  // Write characteristics of the data
  file << "DATASET STRUCTURED_POINTS\n";
  if ( numDims == 2 )
    {
    file << "DIMENSIONS " << this->GetDimensions(0) << " "
         << this->GetDimensions(1) << " 1\n";
    file << "SPACING " << m_Spacing[0] << " " << m_Spacing[1] << " 1.0\n";
    file << "ORIGIN " << m_Origin[0] << " " << m_Origin[1] << " 0.0\n";
    }
  else //numDims == 3
    {
    file << "DIMENSIONS " << this->GetDimensions(0) << " "
         << this->GetDimensions(1) << " " << this->GetDimensions(2) << "\n";
    file << "SPACING " << m_Spacing[0] << " "
         << m_Spacing[1] << " " << m_Spacing[2] << "\n";
    file << "ORIGIN " << m_Origin[0] << " "
         << m_Origin[1] << " " << m_Origin[2] << "\n";
    }

  file << "POINT_DATA " << this->GetImageSizeInPixels() << "\n";
  file << "SCALARS scalars "
       << this->ReturnTypeAsString(this->GetComponentType()) << " "
       << this->GetNumberOfComponents() << "\n";
  file << "LOOKUP_TABLE default\n";

  // Write the actual pixel data
  if ( m_FileType == ASCII )
    {
    this->WriteBufferAsASCII(file, buffer, this->GetComponentType(),
                            this->GetImageSizeInComponents());
    }
  else //binary
    {
    file.write(static_cast<char*>(buffer), this->GetImageSizeInBytes());
    }
}

void VTKImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

} // end namespace itk
<commit_msg>ERR: unsigned/signed comparision.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkVTKImageIO.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.

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

=========================================================================*/
#include "itkVTKImageIO.h"
#include <stdio.h>

namespace itk
{

VTKImageIO::VTKImageIO()
{
  this->SetNumberOfDimensions(2);
  m_ByteOrder = LittleEndian;
  m_FileType = ASCII;

}

VTKImageIO::~VTKImageIO()
{
}

bool VTKImageIO::OpenVTKFileForReading(std::ifstream& os,
                                       const char* filename)

{
  // Make sure that we have a file to
  if ( filename == "" )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    return false;
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for reading
  itkDebugMacro(<< "Initialize: opening file " << filename);

  // Actually open the file
  int openMode = std::ios::in;

#ifdef _WIN32
  openMode |= std::ios::binary;
#endif
#if defined(__GNUC__) && __GNUC__ >= 3
  os.open(filename, static_cast<std::ios_base::openmode>(openMode));
#else
  os.open(filename, openMode);
#endif
  if ( os.fail() )
    {
    itkExceptionMacro(<< "Could not open file for reading: " << filename);
    return false;
    }

  return true;
}

bool VTKImageIO::OpenVTKFileForWriting(std::ofstream& os,
                                       const char* filename)

{
  // Make sure that we have a file to
  if ( filename == "" )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    return false;
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for writing
  itkDebugMacro(<< "Initialize: opening file " << filename);

  // Actually open the file
  int openMode = std::ios::out;

#ifdef _WIN32
  openMode |= std::ios::binary;
#endif
#if defined(__GNUC__) && __GNUC__ >= 3
  os.open(filename, static_cast<std::ios_base::openmode>(openMode));
#else
  os.open(filename, openMode);
#endif
  if ( os.fail() )
    {
    itkExceptionMacro(<< "Could not open file for writing: " << filename);
    return false;
    }

  return true;
}

bool VTKImageIO::CanReadFile(const char* filename)
{
  std::ifstream file;
  char buffer[256];
  std::string fname(filename);

  if ( fname.find(".vtk") >= fname.length() )
    {
    return false;
    }

  if ( ! this->OpenVTKFileForReading(file, filename) )
    {
    return false;
    }

  // Check to see if its a vtk structured points file
  file.getline(buffer,255);
  file.getline(buffer,255);
  file.getline(buffer,255);
  file.getline(buffer,255);

  fname = buffer;

  if ( fname.find("STRUCTURED_POINTS") < fname.length() ||
       fname.find("structured_points") < fname.length() )
    {
    return true;
    }
  else
    {
    return false;
    }
}

void VTKImageIO::Read(void* buffer)
{
  std::ifstream file;
  char line[255];
  std::string text;

  // Check the input
  //
  if ( ! this->OpenVTKFileForReading(file, m_FileName.c_str()) )
    {
    itkExceptionMacro(<< "Cannot read requested file");
    }

  file.getline(line,255);
  file.getline(line,255);
  file.getline(line,255);
  text = line;
  if ( text.find("ASCII") < text.length() ||
       text.find("ascii") < text.length() )
    {
    this->SetFileTypeToASCII();
    }
  else if ( text.find("BINARY") < text.length() ||
            text.find("binary") < text.length() )
    {
    this->SetFileTypeToBinary();
    }
  else
    {
    itkExceptionMacro(<< "Unrecognized type");
    }
  file.getline(line,255);
  text = line;
  if ( text.find("STRUCTURED_POINTS") >= text.length() &&
       text.find("structured_points") >= text.length() )
    {
    itkExceptionMacro(<< "Not structured points, can't read");
    }

  //extract dimensions, spacing, origin
  unsigned int dims[3];
  float spacing[3];
  float origin[3];
  file.getline(line,255);
  text = line;
  unsigned int i;

  if ( text.find("DIMENSIONS") < text.length() ||
       text.find("dimensions") < text.length() )
    {
    sscanf(line, "%*s %d %d %d", dims, dims+1, dims+2);
    if ( dims[2] <= 1 )
      {
      this->SetNumberOfDimensions(2);
      }
    else
      {
      this->SetNumberOfDimensions(3);
      }
    for ( i=0; i < m_NumberOfDimensions; i++ )
      {
      m_Dimensions[i] = dims[i];
      }
    }
  else
    {
    itkExceptionMacro(<<"No dimensions defined");
    }

  file.getline(line,255);
  text = line;
  if ( text.find("SPACING") < text.length() ||
       text.find("spacing") < text.length() )
    {
    sscanf(line, "%*s %f %f %f", spacing, spacing+1, spacing+2);
    for ( i=0; i < m_NumberOfDimensions; i++ )
      {
      m_Spacing[i] = spacing[i];
      }
    }
  else
    {
    itkExceptionMacro(<<"No spacing defined");
    }

  file.getline(line,255);
  text = line;
  if ( text.find("ORIGIN") < text.length() ||
       text.find("origin") < text.length() )
    {
    sscanf(line, "%*s %f %f %f", origin, origin+1, origin+2);
    for ( i=0; i < m_NumberOfDimensions; i++ )
      {
      m_Origin[i] = origin[i];
      }
    }
  else
    {
    itkExceptionMacro(<<"No origin defined");
    }

  //Now grab the data; need to determine the pixel type
  file.getline(line,255);
  text = line;
  while ( text.find("SCALARS") >= text.length() ||
          text.find("scalars") >= text.length() )
    {
    file.getline(line,255);
    text = line;
    }
  char pixelType[256];
  sscanf(line, "%*s %*s %s", pixelType);
  text = pixelType;
  if ( text.find("float") < text.length() )
    {
    SetPixelType(FLOAT);
    SetComponentType(FLOAT);
    }
  else if ( text.find("double") < text.length() )
    {
    SetPixelType(DOUBLE);
    SetComponentType(DOUBLE);
    }
  else if ( text.find("unsigned_char") < text.length() )
    {
    SetPixelType(UCHAR);
    SetComponentType(UCHAR);
    }
  else if ( text.find("char") < text.length() )
    {
    SetPixelType(CHAR);
    SetComponentType(CHAR);
    }
  else if ( text.find("unsigned_short") < text.length() )
    {
    SetPixelType(USHORT);
    SetComponentType(USHORT);
    }
  else if ( text.find("short") < text.length() )
    {
    SetPixelType(SHORT);
    SetComponentType(SHORT);
    }
  else if ( text.find("unsigned_int") < text.length() )
    {
    SetPixelType(UINT);
    SetComponentType(UINT);
    }
  else if ( text.find("int") < text.length() )
    {
    SetPixelType(INT);
    SetComponentType(INT);
    }
  else if ( text.find("unsigned_long") < text.length() )
    {
    SetPixelType(ULONG);
    SetComponentType(ULONG);
    }
  else if ( text.find("long") < text.length() )
    {
    SetPixelType(LONG);
    SetComponentType(LONG);
    }
  else
    {
    itkExceptionMacro(<<"Unrecognized type");
    }

  // grab the trailing lookup table line
  file.getline(line,255);
  //We are positioned at the data. The data is read depending on whether
  //it is ASCII or binary.
  if ( m_FileType == ASCII )
    {
    this->ReadBufferAsASCII(file, buffer, this->GetComponentType(),
                            this->GetImageSizeInComponents());
    }
  else
    {
    file.read(static_cast<char*>(buffer), this->GetImageSizeInBytes());
    }
}

void VTKImageIO::ReadImageInformation()
{
}

bool VTKImageIO::CanWriteFile(const char*)
{
  if ( m_FileName != "" &&
       m_FileName.find(".vtk") < m_FileName.length() )
    {
    return true;
    }
  return false;
}

void VTKImageIO::Write(void* buffer)
{
  std::ofstream file;
  if ( ! this->OpenVTKFileForWriting(file,m_FileName.c_str()) )
    {
    return;
    }

  // Check the image region for proper dimensions, etc.
  unsigned int numDims = this->GetNumberOfDimensions();
  if ( numDims < 2 || numDims > 3 )
    {
    itkExceptionMacro(<<"VTK Writer can only write 2 or 3-dimensional images");
    return;
    }
  ImageIORegion ioRegion = this->GetIORegion();

  // Write the VTK header information
  file << "# vtk DataFile Version 3.0\n";
  file << "VTK File Generated by Insight Segmentation and Registration Toolkit (ITK)\n";

  if ( this->GetFileType() == ASCII ) { file << "ASCII\n"; }
  else { file << "BINARY\n"; }

  // Write characteristics of the data
  file << "DATASET STRUCTURED_POINTS\n";
  if ( numDims == 2 )
    {
    file << "DIMENSIONS " << this->GetDimensions(0) << " "
         << this->GetDimensions(1) << " 1\n";
    file << "SPACING " << m_Spacing[0] << " " << m_Spacing[1] << " 1.0\n";
    file << "ORIGIN " << m_Origin[0] << " " << m_Origin[1] << " 0.0\n";
    }
  else //numDims == 3
    {
    file << "DIMENSIONS " << this->GetDimensions(0) << " "
         << this->GetDimensions(1) << " " << this->GetDimensions(2) << "\n";
    file << "SPACING " << m_Spacing[0] << " "
         << m_Spacing[1] << " " << m_Spacing[2] << "\n";
    file << "ORIGIN " << m_Origin[0] << " "
         << m_Origin[1] << " " << m_Origin[2] << "\n";
    }

  file << "POINT_DATA " << this->GetImageSizeInPixels() << "\n";
  file << "SCALARS scalars "
       << this->ReturnTypeAsString(this->GetComponentType()) << " "
       << this->GetNumberOfComponents() << "\n";
  file << "LOOKUP_TABLE default\n";

  // Write the actual pixel data
  if ( m_FileType == ASCII )
    {
    this->WriteBufferAsASCII(file, buffer, this->GetComponentType(),
                            this->GetImageSizeInComponents());
    }
  else //binary
    {
    file.write(static_cast<char*>(buffer), this->GetImageSizeInBytes());
    }
}

void VTKImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

} // end namespace itk
<|endoftext|>


<commit_before>#include "TextLabel.hpp"

#include "../App.hpp"

using namespace morda;

TextLabel::TextLabel(){
	this->font = App::Inst().ResMan().Load<morda::ResFont>("fnt_main");
}

void TextLabel::SetText(const std::string& text){
	this->text = text;

	tride::Rect2f bb = this->font->Fnt().StringBoundingBox(this->text);

	this->pivot = -bb.p;
	this->Resize(bb.d);
}

//override
void TextLabel::Render(const tride::Matr4f& matrix)const{
	{
		tride::Matr4f matr(matrix);
		matr.Scale(this->Rect().d);
		SimpleSingleColoringShader& s = App::Inst().shaders.simpleSingleColoring;
		s.Bind();
		s.SetColor(tride::Vec3f(0.5, 0.5, 0.5));
		s.SetMatrix(matr);
		s.DrawQuad01();
	}

	//render text
	morda::SimpleTexturingShader &s = morda::App::Inst().shaders.simpleTexturing;
	s.Bind();

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	tride::Matr4f matr(matrix);
	matr.Translate(this->pivot);
	this->font->Fnt().RenderString(s, matr, this->text);
}
<commit_msg>commenting debug code<commit_after>#include "TextLabel.hpp"

#include "../App.hpp"

using namespace morda;

TextLabel::TextLabel(){
	this->font = App::Inst().ResMan().Load<morda::ResFont>("fnt_main");
}

void TextLabel::SetText(const std::string& text){
	this->text = text;

	tride::Rect2f bb = this->font->Fnt().StringBoundingBox(this->text);

	this->pivot = -bb.p;
	this->Resize(bb.d);
}

//override
void TextLabel::Render(const tride::Matr4f& matrix)const{
//	{
//		tride::Matr4f matr(matrix);
//		matr.Scale(this->Rect().d);
//		SimpleSingleColoringShader& s = App::Inst().shaders.simpleSingleColoring;
//		s.Bind();
//		s.SetColor(tride::Vec3f(0.5, 0.5, 0.5));
//		s.SetMatrix(matr);
//		s.DrawQuad01();
//	}

	//render text
	morda::SimpleTexturingShader &s = morda::App::Inst().shaders.simpleTexturing;
	s.Bind();

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	tride::Matr4f matr(matrix);
	matr.Translate(this->pivot);
	this->font->Fnt().RenderString(s, matr, this->text);
}
<|endoftext|>