<commit_before>#pragma once

#include <cstdint>

#ifdef HOST_PYTHON_MODULE
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

namespace py = pybind11;
#endif

#define MAX_OBJECTS (20)

enum TrackingStatus
{
    NEW = 0,         /**< The object is newly added. */
    TRACKED,     /**< The object is being tracked. */
    LOST         /**< The object gets lost now. The object can be tracked again automatically(long term tracking) or by specifying detected object manually(short term and zero term tracking). */
};

typedef struct ImgRoi
{
    int32_t left;
    int32_t top;
    int32_t right;
    int32_t bottom;
}ImgRoi;

struct Tracklet {
    ImgRoi roi;
    int64_t id;
    int32_t label;
    int32_t status;

private:

public:

    int64_t getId(void){
        return id;
    }

    int32_t getLabel(void){
        return label;
    }

    std::string getStatus(void){
        std::vector<std::string> status_str = {"NEW", "TRACKED", "LOST"};
        if(status < 0 || status > 3) assert(0);
        return status_str.at(status);
    }

    int32_t getLeftCoord(void){
        return roi.left;
    }

    int32_t getTopCoord(void){
        return roi.top;
    }

    int32_t getRightCoord(void){
        return roi.right;
    }

    int32_t getBottomCoord(void){
        return roi.bottom;
    }

};

struct ObjectTracker {

    int nr_tracklets;
    Tracklet tracklet[MAX_OBJECTS];

private:

public:

    int getNrTracklets(){
        assert(nr_tracklets < MAX_OBJECTS);
        return nr_tracklets;
    }
#ifdef HOST_PYTHON_MODULE
    py::object getTracklet(int tracklet_nr)
    {
        assert(tracklet_nr < nr_tracklets);
        return py::cast<Tracklet>(tracklet[tracklet_nr]);
    }
#else
    Tracklet getTracklet(int tracklet_nr)
    {
        assert(tracklet_nr < nr_tracklets);
        return tracklet[tracklet_nr];
    }
#endif

};<commit_msg>Updated object tracker<commit_after>#pragma once

#include <cstdint>

#ifdef HOST_PYTHON_MODULE
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

namespace py = pybind11;
#endif

#define MAX_OBJECTS (20)

enum TrackingStatus
{
    NEW = 0,         /**< The object is newly added. */
    TRACKED,     /**< The object is being tracked. */
    LOST         /**< The object gets lost now. The object can be tracked again automatically(long term tracking) or by specifying detected object manually(short term and zero term tracking). */
};

typedef struct ImgRoi
{
    int32_t left;
    int32_t top;
    int32_t right;
    int32_t bottom;
}ImgRoi;

struct Tracklet {
    ImgRoi roi;
    int64_t id;
    int32_t label;
    int32_t status;

private:

public:

    int64_t getId(void){
        return id;
    }

    int32_t getLabel(void){
        return label;
    }

    std::string getStatus(void){
        std::vector<std::string> status_str = {"NEW", "TRACKED", "LOST"};
        if(status < 0 || status > 3) assert(0);
        return status_str.at(status);
    }

    int32_t getLeftCoord(void){
        return roi.left;
    }

    int32_t getTopCoord(void){
        return roi.top;
    }

    int32_t getRightCoord(void){
        return roi.right;
    }

    int32_t getBottomCoord(void){
        return roi.bottom;
    }

};

struct ObjectTracker {

    int nr_tracklets;
    Tracklet tracklet[MAX_OBJECTS];

private:

public:

    int getNrTracklets(){
        assert(nr_tracklets <= MAX_OBJECTS);
        return nr_tracklets;
    }
#ifdef HOST_PYTHON_MODULE
    py::object getTracklet(int tracklet_nr)
    {
        assert(tracklet_nr < nr_tracklets);
        return py::cast<Tracklet>(tracklet[tracklet_nr]);
    }
#else
    Tracklet getTracklet(int tracklet_nr)
    {
        assert(tracklet_nr < nr_tracklets);
        return tracklet[tracklet_nr];
    }
#endif

};<|endoftext|>


<commit_before>#include "dockmanagermodel.h"
#include <QString>
#include <QMainWindow>
#include "dockmanager.h"
#include "dock.h"

DockManagerModel::DockManagerModel (DockManager & mgr, QObject * parent, tree_data_t * data)
	: TreeModel<DockedInfo>(parent, data)
	, m_manager(mgr)
{
	qDebug("%s", __FUNCTION__);
}

DockManagerModel::~DockManagerModel ()
{
	qDebug("%s", __FUNCTION__);
}
QModelIndex DockManagerModel::testItemWithPath (QStringList const & path)
{
	QString const name = path.join("/");
	DockedInfo const * i = 0;
	if (node_t const * node = m_tree_data->is_present(name, i))
		return indexFromItem(node);
	else
		return QModelIndex();
}

QModelIndex DockManagerModel::insertItemWithPath (QStringList const & path, bool checked)
{
	QString const name = path.join("/");
	DockedInfo const * i = 0;
	node_t const * node = m_tree_data->is_present(name, i);
	if (node)
	{
		//qDebug("%s path=%s already present", __FUNCTION__, path.toStdString().c_str());
		return indexFromItem(node);
	}
	else
	{
		//qDebug("%s path=%s not present, adding", __FUNCTION__, path.toStdString().c_str());
		DockedInfo i;
		i.m_state = checked ? Qt::Checked : Qt::Unchecked;
		i.m_collapsed = false;
		//i.m_path = path;

		node_t * const n = m_tree_data->set_to_state(name, i);
		QModelIndex const parent_idx = indexFromItem(n->parent);
		//int const last = n->parent->count_childs() - 1;
		beginInsertRows(parent_idx, 0, 0);
		n->data.m_path = path;

		QModelIndex const idx = indexFromItem(n);
		endInsertRows();
		initData(idx, checked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
		//QModelIndex const parent_idx = idx.parent();
		//if (parent_idx.isValid())
		//	emit dataChanged(parent_idx, parent_idx);
		return idx;
	}
}

int DockManagerModel::columnCount (QModelIndex const & parent) const
{
	return DockManager::e_max_dockmgr_column;
}

Qt::ItemFlags DockManagerModel::flags (QModelIndex const & index) const
{
	return QAbstractItemModel::flags(index)
				| Qt::ItemIsEnabled
				| Qt::ItemIsUserCheckable
				| Qt::ItemIsSelectable;
}

/*DockedWidgetBase const * DockManagerModel::getWidgetFromIndex (QModelIndex const & index) const
{
	DockManager const * const mgr = static_cast<DockManager const *>(QObject::parent());
	node_t const * const item = itemFromIndex(index);
	QStringList const & p = item->data.m_path;
	DockedWidgetBase const * const dwb = m_manager.findDockable(p.join("/"));
	return dwb;
}

DockedWidgetBase * DockManagerModel::getWidgetFromIndex (QModelIndex const & index)
{
	DockManager * const mgr = static_cast<DockManager *>(QObject::parent());
	node_t const * const item = itemFromIndex(index);
	QStringList const & p = item->data.m_path;
	DockedWidgetBase * dwb = m_manager.findDockable(p.join("/"));
	return dwb;
}*/

QVariant DockManagerModel::data (QModelIndex const & index, int role) const
{
	if (!index.isValid())
		return QVariant();

	int const col = index.column();
	if (col == DockManager::e_Column_Name)
		return TreeModel<DockedInfo>::data(index, role);
	return QVariant();
}

bool DockManagerModel::setData (QModelIndex const & index, QVariant const & value, int role)
{
	if (!index.isValid()) return false;

	if (role == Qt::CheckStateRole)
	{
		node_t const * const n = itemFromIndex(index);
		QStringList const & dst = n->data.m_path;

		Action a;
		a.m_type = e_Visibility;
		a.m_src_path = m_manager.path();
		a.m_src = &m_manager;
		a.m_dst_path = dst;

		int const state = value.toInt();
		a.m_args.push_back(state);
		m_manager.handleAction(&a, e_Sync);
	}

	return TreeModel<DockedInfo>::setData(index, value, role);
}

bool DockManagerModel::initData (QModelIndex const & index, QVariant const & value, int role)
{
	return TreeModel<DockedInfo>::setData(index, value, role);
}

<commit_msg>* fixed row insert<commit_after>#include "dockmanagermodel.h"
#include <QString>
#include <QMainWindow>
#include "dockmanager.h"
#include "dock.h"

DockManagerModel::DockManagerModel (DockManager & mgr, QObject * parent, tree_data_t * data)
	: TreeModel<DockedInfo>(parent, data)
	, m_manager(mgr)
{
	qDebug("%s", __FUNCTION__);
}

DockManagerModel::~DockManagerModel ()
{
	qDebug("%s", __FUNCTION__);
}
QModelIndex DockManagerModel::testItemWithPath (QStringList const & path)
{
	QString const name = path.join("/");
	DockedInfo const * i = 0;
	if (node_t const * node = m_tree_data->is_present(name, i))
		return indexFromItem(node);
	else
		return QModelIndex();
}

QModelIndex DockManagerModel::insertItemWithPath (QStringList const & path, bool checked)
{
	QString const name = path.join("/");
	DockedInfo const * i = 0;
	node_t const * node = m_tree_data->is_present(name, i);
	if (node)
	{
		//qDebug("%s path=%s already present", __FUNCTION__, path.toStdString().c_str());
		return indexFromItem(node);
	}
	else
	{
		//qDebug("%s path=%s not present, adding", __FUNCTION__, path.toStdString().c_str());
		DockedInfo i;
		i.m_state = checked ? Qt::Checked : Qt::Unchecked;
		i.m_collapsed = false;
		//i.m_path = path;

		node_t * const n = m_tree_data->set_to_state(name, i);
		QModelIndex const parent_idx = indexFromItem(n->parent);
		int const last = n->parent->count_childs() - 1;
		beginInsertRows(parent_idx, last, last);
		n->data.m_path = path;

		QModelIndex const idx = indexFromItem(n);
		endInsertRows();
		initData(idx, checked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
		//QModelIndex const parent_idx = idx.parent();
		//if (parent_idx.isValid())
		//	emit dataChanged(parent_idx, parent_idx);
		return idx;
	}
}

int DockManagerModel::columnCount (QModelIndex const & parent) const
{
	return DockManager::e_max_dockmgr_column;
}

Qt::ItemFlags DockManagerModel::flags (QModelIndex const & index) const
{
	return QAbstractItemModel::flags(index)
				| Qt::ItemIsEnabled
				| Qt::ItemIsUserCheckable
				| Qt::ItemIsSelectable;
}

/*DockedWidgetBase const * DockManagerModel::getWidgetFromIndex (QModelIndex const & index) const
{
	DockManager const * const mgr = static_cast<DockManager const *>(QObject::parent());
	node_t const * const item = itemFromIndex(index);
	QStringList const & p = item->data.m_path;
	DockedWidgetBase const * const dwb = m_manager.findDockable(p.join("/"));
	return dwb;
}

DockedWidgetBase * DockManagerModel::getWidgetFromIndex (QModelIndex const & index)
{
	DockManager * const mgr = static_cast<DockManager *>(QObject::parent());
	node_t const * const item = itemFromIndex(index);
	QStringList const & p = item->data.m_path;
	DockedWidgetBase * dwb = m_manager.findDockable(p.join("/"));
	return dwb;
}*/

QVariant DockManagerModel::data (QModelIndex const & index, int role) const
{
	if (!index.isValid())
		return QVariant();

	int const col = index.column();
	if (col == DockManager::e_Column_Name)
		return TreeModel<DockedInfo>::data(index, role);
	return QVariant();
}

bool DockManagerModel::setData (QModelIndex const & index, QVariant const & value, int role)
{
	if (!index.isValid()) return false;

	if (role == Qt::CheckStateRole)
	{
		node_t const * const n = itemFromIndex(index);
		QStringList const & dst = n->data.m_path;

		Action a;
		a.m_type = e_Visibility;
		a.m_src_path = m_manager.path();
		a.m_src = &m_manager;
		a.m_dst_path = dst;

		int const state = value.toInt();
		a.m_args.push_back(state);
		m_manager.handleAction(&a, e_Sync);
	}

	return TreeModel<DockedInfo>::setData(index, value, role);
}

bool DockManagerModel::initData (QModelIndex const & index, QVariant const & value, int role)
{
	return TreeModel<DockedInfo>::setData(index, value, role);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fstat.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:16:16 $
 *
 *  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
 *
 ************************************************************************/

#if defined( WIN)
#include <stdio.h>
#include <dos.h>
#endif

#ifdef UNX
#include <errno.h>
#endif

#include <limits.h>
#include <string.h>

#include "comdep.hxx"
#include <fsys.hxx>

/*************************************************************************
|*
|*    FileStat::FileStat()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 11.06.91
|*    Letzte Aenderung  MI 11.06.91
|*
*************************************************************************/

FileStat::FileStat()
:   // don't use Default-Ctors!
    aDateCreated( ULONG(0) ),
    aTimeCreated( ULONG(0) ),
    aDateModified( ULONG(0) ),
    aTimeModified( ULONG(0) ),
    aDateAccessed( ULONG(0) ),
    aTimeAccessed( ULONG(0) )
{
    nSize = 0;
    nKindFlags = FSYS_KIND_UNKNOWN;
    nError = FSYS_ERR_OK;
}

/*************************************************************************
|*
|*    FileStat::FileStat()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 11.06.91
|*    Letzte Aenderung  MI 11.06.91
|*
*************************************************************************/

FileStat::FileStat( const DirEntry& rDirEntry, FSysAccess nAccess )
:   // don't use Default-Ctors!
    aDateCreated( ULONG(0) ),
    aTimeCreated( ULONG(0) ),
    aDateModified( ULONG(0) ),
    aTimeModified( ULONG(0) ),
    aDateAccessed( ULONG(0) ),
    aTimeAccessed( ULONG(0) )
{
    BOOL bCached = FSYS_ACCESS_CACHED == (nAccess & FSYS_ACCESS_CACHED);
    BOOL bFloppy = FSYS_ACCESS_FLOPPY == (nAccess & FSYS_ACCESS_FLOPPY);

#ifdef FEAT_FSYS_DOUBLESPEED
    const FileStat *pStatFromDir = bCached ? rDirEntry.ImpGetStat() : 0;
    if ( pStatFromDir )
    {
        nError = pStatFromDir->nError;
        nKindFlags = pStatFromDir->nKindFlags;
        nSize = pStatFromDir->nSize;
        aCreator = pStatFromDir->aCreator;
        aType = pStatFromDir->aType;
        aDateCreated = pStatFromDir->aDateCreated;
        aTimeCreated = pStatFromDir->aTimeCreated;
        aDateModified = pStatFromDir->aDateModified;
        aTimeModified = pStatFromDir->aTimeModified;
        aDateAccessed = pStatFromDir->aDateAccessed;
        aTimeAccessed = pStatFromDir->aTimeAccessed;
    }
    else
#endif
        Update( rDirEntry, bFloppy );
}

/*************************************************************************
|*
|*    FileStat::IsYounger()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MA 11.11.91
|*    Letzte Aenderung  MA 11.11.91
|*
*************************************************************************/

// TRUE  wenn die Instanz j"unger als rIsOlder ist.
// FALSE wenn die Instanz "alter oder gleich alt wie rIsOlder ist.

BOOL FileStat::IsYounger( const FileStat& rIsOlder ) const
{
    if ( aDateModified > rIsOlder.aDateModified )
        return TRUE;
    if ( ( aDateModified == rIsOlder.aDateModified ) &&
         ( aTimeModified > rIsOlder.aTimeModified ) )
        return TRUE;

    return FALSE;
}

/*************************************************************************
|*
|*    FileStat::IsKind()
|*
|*    Ersterstellung    MA 11.11.91 (?)
|*    Letzte Aenderung  KH 16.01.95
|*
*************************************************************************/

BOOL FileStat::IsKind( DirEntryKind nKind ) const
{
    BOOL bRet = ( ( nKind == FSYS_KIND_UNKNOWN ) &&
                  ( nKindFlags == FSYS_KIND_UNKNOWN ) ) ||
                   ( ( nKindFlags & nKind ) == nKind );
    return bRet;
}

/*************************************************************************
|*
|*    FileStat::HasReadOnlyFlag()
|*
|*    Ersterstellung    MI 06.03.97
|*    Letzte Aenderung  UT 01.07.98
|*
*************************************************************************/

BOOL FileStat::HasReadOnlyFlag()
{
#if defined(WNT) || defined(OS2) || defined(UNX)
    return TRUE;
#else
    return FALSE;
#endif
}

/*************************************************************************
|*
|*    FileStat::GetReadOnlyFlag()
|*
|*    Ersterstellung    MI 06.03.97
|*    Letzte Aenderung  UT 02.07.98
|*
*************************************************************************/

BOOL FileStat::GetReadOnlyFlag( const DirEntry &rEntry )
{

    ByteString aFPath(rEntry.GetFull(), osl_getThreadTextEncoding());
#ifdef WNT
    DWORD nRes = GetFileAttributes( (LPCTSTR) aFPath.GetBuffer() );
    return ULONG_MAX != nRes &&
           ( FILE_ATTRIBUTE_READONLY & nRes ) == FILE_ATTRIBUTE_READONLY;
#endif

#ifdef OS2
    FILESTATUS3 aFileStat;
    APIRET nRet = DosQueryPathInfo( (PSZ)aFPath.GetBuffer(), 1, &aFileStat, sizeof(aFileStat) );
    switch ( nRet )
    {
        case NO_ERROR:
            return FILE_READONLY == ( aFileStat.attrFile & FILE_READONLY );

        case ERROR_SHARING_VIOLATION:
            return ERRCODE_IO_LOCKVIOLATION;

        default:
            return ERRCODE_IO_NOTEXISTS;
    }
#endif

#ifdef UNX
    /* could we stat the object? */
    struct stat aBuf;
    if (stat(aFPath.GetBuffer(), &aBuf))
        return FALSE;
    /* jupp, is writable for user? */
    return((aBuf.st_mode & S_IWUSR) != S_IWUSR);
#endif
    return FALSE;
}

/*************************************************************************
|*
|*    FileStat::SetReadOnlyFlag()
|*
|*    Ersterstellung    MI 06.03.97
|*    Letzte Aenderung  UT 01.07.98
|*
*************************************************************************/

ULONG FileStat::SetReadOnlyFlag( const DirEntry &rEntry, BOOL bRO )
{

    ByteString aFPath(rEntry.GetFull(), osl_getThreadTextEncoding());

#ifdef WNT
    DWORD nRes = GetFileAttributes( (LPCTSTR) aFPath.GetBuffer() );
    if ( ULONG_MAX != nRes )
        nRes = SetFileAttributes( (LPCTSTR) aFPath.GetBuffer(),
                    ( nRes & ~FILE_ATTRIBUTE_READONLY ) |
                    ( bRO ? FILE_ATTRIBUTE_READONLY : 0 ) );
    return ( ULONG_MAX == nRes ) ? ERRCODE_IO_UNKNOWN : 0;
#endif

#ifdef OS2
    FILESTATUS3 aFileStat;
    APIRET nRet = DosQueryPathInfo( (PSZ)aFPath.GetBuffer(), 1, &aFileStat, sizeof(aFileStat) );
    if ( !nRet )
    {
        aFileStat.attrFile = ( aFileStat.attrFile & ~FILE_READONLY ) |
                             ( bRO ? FILE_READONLY : 0 );
        nRet = DosSetPathInfo( (PSZ)aFPath.GetBuffer(), 1, &aFileStat, sizeof(aFileStat), 0 );
    }
    switch ( nRet )
    {
        case NO_ERROR:
            return ERRCODE_NONE;

        case ERROR_SHARING_VIOLATION:
            return ERRCODE_IO_LOCKVIOLATION;

        default:
            return ERRCODE_IO_NOTEXISTS;
    }
#endif

#ifdef UNX
    /* first, stat the object to get permissions */
    struct stat aBuf;
    if (stat(aFPath.GetBuffer(), &aBuf))
        return ERRCODE_IO_NOTEXISTS;
    /* set or clear write bit for user */
    mode_t nMode;
    if (bRO)
    {
        nMode = aBuf.st_mode & ~S_IWUSR;
        nMode = aBuf.st_mode & ~S_IWGRP;
        nMode = aBuf.st_mode & ~S_IWOTH;
    }
    else
        nMode = aBuf.st_mode | S_IWUSR;
    /* change it on fs */
    if (chmod(aFPath.GetBuffer(), nMode))
    {
        switch (errno)
        {
            case EPERM :
            case EROFS :
                return ERRCODE_IO_ACCESSDENIED;
            default    :
                return ERRCODE_IO_NOTEXISTS;
        }
    }
    else
        return ERRCODE_NONE;
#endif
    return ERRCODE_IO_NOTSUPPORTED;
}

/*************************************************************************
|*
|*    FileStat::SetDateTime
|*
|*    Ersterstellung    PB  27.06.97
|*    Letzte Aenderung
|*
*************************************************************************/
#if defined(WIN) | defined(WNT) | defined(OS2)

void FileStat::SetDateTime( const String& rFileName,
                            const DateTime& rNewDateTime )
{
    ByteString aFileName(rFileName, osl_getThreadTextEncoding());

    Date aNewDate = rNewDateTime;
    Time aNewTime = rNewDateTime;
#if defined(WIN)
    unsigned date = 0;
    unsigned time = 0;

    date  = (unsigned) aNewDate.GetDay();
    date |= (unsigned)(aNewDate.GetMonth() << 5);
    date |= (unsigned)((aNewDate.GetYear() -  1980) << 9);
    time  = (unsigned)(aNewTime.GetSec() / 2);
    time |= (unsigned)(aNewTime.GetMin() << 5);
    time |= (unsigned)(aNewTime.GetHour() << 11);

    FILE* pFile = fopen( aFileName.GetBuffer(), "a" );

    if ( pFile != NULL )
    {
        _dos_setftime( fileno(pFile), date, time );
        fclose( pFile );
    }

#elif defined( WNT )

    TIME_ZONE_INFORMATION aTZI;
    DWORD dwTZI = GetTimeZoneInformation( &aTZI );

    if ( dwTZI != (DWORD)-1 && dwTZI != TIME_ZONE_ID_UNKNOWN )
    {
        // 1. Korrektur der Zeitzone
        short nDiff = (short)aTZI.Bias;
        Time aOldTime = aNewTime; // alte Zeit merken

        // 2. evt. Korrektur Sommer-/Winterzeit
        if ( dwTZI == TIME_ZONE_ID_DAYLIGHT )
            nDiff += (short)aTZI.DaylightBias;

        Time aDiff( abs( nDiff / 60 /*Min -> Std*/ ), 0 );

        if ( nDiff > 0 )
        {
            aNewTime += aDiff;                  // Stundenkorrektur

            // bei "Uberlauf korrigieren
            if ( aNewTime >= Time( 24, 0 ) )
                aNewTime -= Time( 24, 0 );

            // Tages"uberlauf?
            if ( aOldTime == Time( 0, 0 ) ||    // 00:00 -> 01:00
                 aNewTime < aOldTime )          // 23:00 -> 00:00 | 01:00 ...
                aNewDate++;
        }
        else if ( nDiff < 0 )
        {
            aNewTime -= aDiff;                  // Stundenkorrektur

            // negative Zeit (-1:00) korrigieren: 23:00
            if (aNewTime < Time( 0, 0 ) )
                aNewTime += Time( 24, 0 );

            // Tagesunterlauf ?
            if ( aOldTime == Time( 0, 0 ) ||    // 00:00 -> 23:00
                 aNewTime > aOldTime )          // 01:00 -> 23:00 | 22:00 ...
                aNewDate--;
        }
    }

    SYSTEMTIME aTime;
    aTime.wYear = aNewDate.GetYear();
    aTime.wMonth = aNewDate.GetMonth();
    aTime.wDayOfWeek = 0;
    aTime.wDay = aNewDate.GetDay();
    aTime.wHour = aNewTime.GetHour();
    aTime.wMinute = aNewTime.GetMin();
    aTime.wSecond = aNewTime.GetSec();
    aTime.wMilliseconds = 0;
    FILETIME aFileTime;
    SystemTimeToFileTime( &aTime, &aFileTime );

    HANDLE hFile = CreateFile( aFileName.GetBuffer(), GENERIC_WRITE, 0, 0,
                               OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 );

    if ( hFile != INVALID_HANDLE_VALUE )
    {
        SetFileTime( hFile, &aFileTime, &aFileTime, &aFileTime );
        CloseHandle( hFile );
    }

#endif
#ifdef OS2
    // open file
    ULONG nAction = FILE_EXISTED;
    HFILE hFile = 0;
    ULONG nFlags = OPEN_FLAGS_WRITE_THROUGH |
                   OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_NO_CACHE   |
                   OPEN_FLAGS_RANDOM        | OPEN_FLAGS_NOINHERIT  |
                   OPEN_SHARE_DENYNONE      | OPEN_ACCESS_READWRITE;

    APIRET nRet = DosOpen((PSZ)aFileName.GetBuffer(), &hFile, (PULONG)&nAction,
                          0/*size*/, FILE_NORMAL,
                          OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS,
                          nFlags, 0/*ea*/);

    if ( nRet == 0 )
    {
        FILESTATUS3 FileInfoBuffer;

        nRet = DosQueryFileInfo(
            hFile, 1, &FileInfoBuffer, sizeof(FileInfoBuffer));

        if ( nRet == 0 )
        {
            FDATE aNewDate;
            FTIME aNewTime;

             // create date and time words
            aNewDate.day     = rNewDateTime.GetDay();
            aNewDate.month   = rNewDateTime.GetMonth();
            aNewDate.year    = rNewDateTime.GetYear() - 1980;
            aNewTime.twosecs = rNewDateTime.GetSec() / 2;
            aNewTime.minutes = rNewDateTime.GetMin();
            aNewTime.hours   = rNewDateTime.GetHour();

            // set file date and time
            FileInfoBuffer.fdateCreation   = aNewDate;
            FileInfoBuffer.ftimeCreation   = aNewTime;
            FileInfoBuffer.fdateLastAccess = aNewDate;
            FileInfoBuffer.ftimeLastAccess = aNewTime;
            FileInfoBuffer.fdateLastWrite  = aNewDate;
            FileInfoBuffer.ftimeLastWrite  = aNewTime;

            DosSetFileInfo(hFile, 1, &FileInfoBuffer, sizeof(FileInfoBuffer));
        }
        DosClose(hFile);
    }
#endif
}

#endif
/*
FileStatMembers *FileStat::GetAllMembers()
{
    FileStatMembers *members = new FileStatMembers;
    members->nError = nError;
    members->nKindFlags = nKindFlags;
    members->nSize = nSize;
    members->aCreator = aCreator;
    members->aType = aType;
    members->aDateCreated = aDateCreated.GetDate();
    members->aTimeCreated = aTimeCreated.GetTime();
    members->aDateAccessed = aDateAccessed.GetDate();
    members->aTimeAccessed = aTimeAccessed.GetTime();
    members->aDateModified = aDateModified.GetDate();
    members->aTimeModified = aTimeModified.GetTime();
    return members;
}

void FileStat::InitMembers(FileStatMembers *members)
{
    nError = members->nError;
    members->nKindFlags = nKindFlags;
    members->nSize = nSize;
    members->aCreator = aCreator;
    members->aType = aType;
    aDateCreated.SetDate(members->aDateCreated);
    aTimeCreated.SetTime(members->aTimeCreated);
    aDateAccessed.SetDate(members->aDateAccessed);
    aTimeAccessed.SetTime(members->aTimeAccessed);
    aDateModified.SetDate(members->aDateModified);
    aTimeModified.SetTime(members->aTimeModified);
}
*/

<commit_msg>INTEGRATION: CWS warnings01 (1.2.8); FILE MERGED 2006/02/24 14:48:53 sb 1.2.8.3: #i53898# Made code warning-free; removed dead code. 2005/10/14 11:19:33 sb 1.2.8.2: #i53898# Made code warning-free; cleanup. 2005/10/13 13:24:28 sb 1.2.8.1: #i53898# Removed code for obsolete platforms.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fstat.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 13:41:19 $
 *
 *  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
 *
 ************************************************************************/

#if defined( WIN)
#include <stdio.h>
#include <dos.h>
#endif

#ifdef UNX
#include <errno.h>
#endif

#include <limits.h>
#include <string.h>

#include "comdep.hxx"
#include <fsys.hxx>

/*************************************************************************
|*
|*    FileStat::FileStat()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 11.06.91
|*    Letzte Aenderung  MI 11.06.91
|*
*************************************************************************/

FileStat::FileStat()
:   // don't use Default-Ctors!
    aDateCreated( ULONG(0) ),
    aTimeCreated( ULONG(0) ),
    aDateModified( ULONG(0) ),
    aTimeModified( ULONG(0) ),
    aDateAccessed( ULONG(0) ),
    aTimeAccessed( ULONG(0) )
{
    nSize = 0;
    nKindFlags = FSYS_KIND_UNKNOWN;
    nError = FSYS_ERR_OK;
}

/*************************************************************************
|*
|*    FileStat::FileStat()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 11.06.91
|*    Letzte Aenderung  MI 11.06.91
|*
*************************************************************************/

FileStat::FileStat( const DirEntry& rDirEntry, FSysAccess nAccess )
:   // don't use Default-Ctors!
    aDateCreated( ULONG(0) ),
    aTimeCreated( ULONG(0) ),
    aDateModified( ULONG(0) ),
    aTimeModified( ULONG(0) ),
    aDateAccessed( ULONG(0) ),
    aTimeAccessed( ULONG(0) )
{
    BOOL bCached = FSYS_ACCESS_CACHED == (nAccess & FSYS_ACCESS_CACHED);
    BOOL bFloppy = FSYS_ACCESS_FLOPPY == (nAccess & FSYS_ACCESS_FLOPPY);

#ifdef FEAT_FSYS_DOUBLESPEED
    const FileStat *pStatFromDir = bCached ? rDirEntry.ImpGetStat() : 0;
    if ( pStatFromDir )
    {
        nError = pStatFromDir->nError;
        nKindFlags = pStatFromDir->nKindFlags;
        nSize = pStatFromDir->nSize;
        aCreator = pStatFromDir->aCreator;
        aType = pStatFromDir->aType;
        aDateCreated = pStatFromDir->aDateCreated;
        aTimeCreated = pStatFromDir->aTimeCreated;
        aDateModified = pStatFromDir->aDateModified;
        aTimeModified = pStatFromDir->aTimeModified;
        aDateAccessed = pStatFromDir->aDateAccessed;
        aTimeAccessed = pStatFromDir->aTimeAccessed;
    }
    else
#endif
        Update( rDirEntry, bFloppy );
}

/*************************************************************************
|*
|*    FileStat::IsYounger()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MA 11.11.91
|*    Letzte Aenderung  MA 11.11.91
|*
*************************************************************************/

// TRUE  wenn die Instanz j"unger als rIsOlder ist.
// FALSE wenn die Instanz "alter oder gleich alt wie rIsOlder ist.

BOOL FileStat::IsYounger( const FileStat& rIsOlder ) const
{
    if ( aDateModified > rIsOlder.aDateModified )
        return TRUE;
    if ( ( aDateModified == rIsOlder.aDateModified ) &&
         ( aTimeModified > rIsOlder.aTimeModified ) )
        return TRUE;

    return FALSE;
}

/*************************************************************************
|*
|*    FileStat::IsKind()
|*
|*    Ersterstellung    MA 11.11.91 (?)
|*    Letzte Aenderung  KH 16.01.95
|*
*************************************************************************/

BOOL FileStat::IsKind( DirEntryKind nKind ) const
{
    BOOL bRet = ( ( nKind == FSYS_KIND_UNKNOWN ) &&
                  ( nKindFlags == FSYS_KIND_UNKNOWN ) ) ||
                   ( ( nKindFlags & nKind ) == nKind );
    return bRet;
}

/*************************************************************************
|*
|*    FileStat::HasReadOnlyFlag()
|*
|*    Ersterstellung    MI 06.03.97
|*    Letzte Aenderung  UT 01.07.98
|*
*************************************************************************/

BOOL FileStat::HasReadOnlyFlag()
{
#if defined WNT || defined UNX
    return TRUE;
#else
    return FALSE;
#endif
}

/*************************************************************************
|*
|*    FileStat::GetReadOnlyFlag()
|*
|*    Ersterstellung    MI 06.03.97
|*    Letzte Aenderung  UT 02.07.98
|*
*************************************************************************/

BOOL FileStat::GetReadOnlyFlag( const DirEntry &rEntry )
{

    ByteString aFPath(rEntry.GetFull(), osl_getThreadTextEncoding());
#if defined WNT
    DWORD nRes = GetFileAttributes( (LPCTSTR) aFPath.GetBuffer() );
    return ULONG_MAX != nRes &&
           ( FILE_ATTRIBUTE_READONLY & nRes ) == FILE_ATTRIBUTE_READONLY;
#elif defined UNX
    /* could we stat the object? */
    struct stat aBuf;
    if (stat(aFPath.GetBuffer(), &aBuf))
        return FALSE;
    /* jupp, is writable for user? */
    return((aBuf.st_mode & S_IWUSR) != S_IWUSR);
#else
    return FALSE;
#endif
}

/*************************************************************************
|*
|*    FileStat::SetReadOnlyFlag()
|*
|*    Ersterstellung    MI 06.03.97
|*    Letzte Aenderung  UT 01.07.98
|*
*************************************************************************/

ULONG FileStat::SetReadOnlyFlag( const DirEntry &rEntry, BOOL bRO )
{

    ByteString aFPath(rEntry.GetFull(), osl_getThreadTextEncoding());

#if defined WNT
    DWORD nRes = GetFileAttributes( (LPCTSTR) aFPath.GetBuffer() );
    if ( ULONG_MAX != nRes )
        nRes = SetFileAttributes( (LPCTSTR) aFPath.GetBuffer(),
                    ( nRes & ~FILE_ATTRIBUTE_READONLY ) |
                    ( bRO ? FILE_ATTRIBUTE_READONLY : 0 ) );
    return ( ULONG_MAX == nRes ) ? ERRCODE_IO_UNKNOWN : 0;
#elif defined UNX
    /* first, stat the object to get permissions */
    struct stat aBuf;
    if (stat(aFPath.GetBuffer(), &aBuf))
        return ERRCODE_IO_NOTEXISTS;
    /* set or clear write bit for user */
    mode_t nMode;
    if (bRO)
    {
        nMode = aBuf.st_mode & ~S_IWUSR;
        nMode = aBuf.st_mode & ~S_IWGRP;
        nMode = aBuf.st_mode & ~S_IWOTH;
    }
    else
        nMode = aBuf.st_mode | S_IWUSR;
    /* change it on fs */
    if (chmod(aFPath.GetBuffer(), nMode))
    {
        switch (errno)
        {
            case EPERM :
            case EROFS :
                return ERRCODE_IO_ACCESSDENIED;
            default    :
                return ERRCODE_IO_NOTEXISTS;
        }
    }
    else
        return ERRCODE_NONE;
#else
    return ERRCODE_IO_NOTSUPPORTED;
#endif
}

/*************************************************************************
|*
|*    FileStat::SetDateTime
|*
|*    Ersterstellung    PB  27.06.97
|*    Letzte Aenderung
|*
*************************************************************************/
#if defined WNT

void FileStat::SetDateTime( const String& rFileName,
                            const DateTime& rNewDateTime )
{
    ByteString aFileName(rFileName, osl_getThreadTextEncoding());

    Date aNewDate = rNewDateTime;
    Time aNewTime = rNewDateTime;

    TIME_ZONE_INFORMATION aTZI;
    DWORD dwTZI = GetTimeZoneInformation( &aTZI );

    if ( dwTZI != (DWORD)-1 && dwTZI != TIME_ZONE_ID_UNKNOWN )
    {
        // 1. Korrektur der Zeitzone
        LONG nDiff = aTZI.Bias;
        Time aOldTime = aNewTime; // alte Zeit merken

        // 2. evt. Korrektur Sommer-/Winterzeit
        if ( dwTZI == TIME_ZONE_ID_DAYLIGHT )
            nDiff += aTZI.DaylightBias;

        Time aDiff( abs( nDiff / 60 /*Min -> Std*/ ), 0 );

        if ( nDiff > 0 )
        {
            aNewTime += aDiff;                  // Stundenkorrektur

            // bei "Uberlauf korrigieren
            if ( aNewTime >= Time( 24, 0 ) )
                aNewTime -= Time( 24, 0 );

            // Tages"uberlauf?
            if ( aOldTime == Time( 0, 0 ) ||    // 00:00 -> 01:00
                 aNewTime < aOldTime )          // 23:00 -> 00:00 | 01:00 ...
                aNewDate++;
        }
        else if ( nDiff < 0 )
        {
            aNewTime -= aDiff;                  // Stundenkorrektur

            // negative Zeit (-1:00) korrigieren: 23:00
            if (aNewTime < Time( 0, 0 ) )
                aNewTime += Time( 24, 0 );

            // Tagesunterlauf ?
            if ( aOldTime == Time( 0, 0 ) ||    // 00:00 -> 23:00
                 aNewTime > aOldTime )          // 01:00 -> 23:00 | 22:00 ...
                aNewDate--;
        }
    }

    SYSTEMTIME aTime;
    aTime.wYear = aNewDate.GetYear();
    aTime.wMonth = aNewDate.GetMonth();
    aTime.wDayOfWeek = 0;
    aTime.wDay = aNewDate.GetDay();
    aTime.wHour = aNewTime.GetHour();
    aTime.wMinute = aNewTime.GetMin();
    aTime.wSecond = aNewTime.GetSec();
    aTime.wMilliseconds = 0;
    FILETIME aFileTime;
    SystemTimeToFileTime( &aTime, &aFileTime );

    HANDLE hFile = CreateFile( aFileName.GetBuffer(), GENERIC_WRITE, 0, 0,
                               OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 );

    if ( hFile != INVALID_HANDLE_VALUE )
    {
        SetFileTime( hFile, &aFileTime, &aFileTime, &aFileTime );
        CloseHandle( hFile );
    }
}
#endif
<|endoftext|>


<commit_before>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#define USE_LAYOUT 1
#define USE_RENDER 1

#include <sbml/packages/render/sbml/RenderInformationBase.h>
#include <sbml/packages/render/sbml/ColorDefinition.h>
#include <sbml/packages/render/sbml/GradientBase.h>
#include <sbml/packages/render/sbml/LinearGradient.h>
#include <sbml/packages/render/sbml/RadialGradient.h>
#include <sbml/packages/render/sbml/LineEnding.h>

#include "CLRenderInformationBase.h"
#include "CLGradientBase.h"
#include "CLLinearGradient.h"
#include "CLRadialGradient.h"

#include "copasi/core/CRootContainer.h"
#include "copasi/report/CKeyFactory.h"

/**
 * Constructor.
 */
CLRenderInformationBase::CLRenderInformationBase(const std::string& name, CDataContainer* pParent):
  CLBase(),
  CDataContainer(name, pParent),
  mKey(""),
  mName("")
{
}

/**
 * Copy constructor.
 */
CLRenderInformationBase::CLRenderInformationBase(const CLRenderInformationBase& source, CDataContainer* pParent):
  CLBase(source),
  CDataContainer(source, pParent),
  mReferenceRenderInformation(source.mReferenceRenderInformation),
  mBackgroundColor(source.mBackgroundColor),
  mListOfColorDefinitions(source.mListOfColorDefinitions, this),
  mListOfGradientDefinitions(source.mListOfGradientDefinitions, this),
  mListOfLineEndings(source.mListOfLineEndings, this),
  mKey(""),
  mName(source.mName)
{
}

/**
 * Constructor to generate object from the corresponding SBML object.
 */
CLRenderInformationBase::CLRenderInformationBase(const RenderInformationBase& source,
    const std::string& name,
    /*
    std::map<std::string,std::string>& colorIdToKeyMap,
    std::map<std::string,std::string>& gradientIdToKeyMap,
    std::map<std::string,std::string>& lineEndingIdToKeyMap,
    */
    CDataContainer* pParent):

  CLBase(),
  CDataContainer(name, pParent),
  mReferenceRenderInformation(source.getReferenceRenderInformationId()),
  mBackgroundColor(source.getBackgroundColor()),
  mKey(""),
  mName(source.getName())
{
  size_t i, iMax = source.getNumColorDefinitions();
  const ColorDefinition* pCD = NULL;
  CLColorDefinition* pLCD = NULL;

  for (i = 0; i < iMax; ++i)
    {
      pCD = source.getColorDefinition((unsigned int) i);
      pLCD = new CLColorDefinition(*pCD);
      this->mListOfColorDefinitions.add(pLCD, true);
      //colorIdToKeyMap.insert(std::pair<std::string,std::string>(pCD->getId(),pLCD->getKey()));
    }

  const GradientBase* pGD = NULL;

  CLGradientBase* pLGD = NULL;

  iMax = source.getNumGradientDefinitions();

  for (i = 0; i < iMax; ++i)
    {
      pGD = source.getGradientDefinition((unsigned int) i);

      if (dynamic_cast<const LinearGradient*>(pGD))
        {
          pLGD = new CLLinearGradient(*static_cast<const LinearGradient*>(pGD));
          this->mListOfGradientDefinitions.add(pLGD, true);
        }
      else if (dynamic_cast<const RadialGradient*>(source.getGradientDefinition((unsigned int) i)))
        {
          pLGD = new CLRadialGradient(*static_cast<const RadialGradient*>(pGD));
          this->mListOfGradientDefinitions.add(pLGD, true);
        }

      //gradientIdToKeyMap.insert(std::pair<std::string,std::string>(pGD->getId(),pLGD->getKey()));
    }

  const LineEnding* pLE = NULL;

  CLLineEnding* pLLE = NULL;

  iMax = source.getNumLineEndings();

  for (i = 0; i < iMax; ++i)
    {
      pLE = source.getLineEnding((unsigned int) i);
      pLLE = new CLLineEnding(*pLE);
      this->mListOfLineEndings.add(pLLE, true);
      //lineEndingIdToKeyMap.insert(std::pair<std::string,std::string>(pLE->getId(),pLLE->getKey()));
    }
}

/**
 * Destructor
 */
CLRenderInformationBase::~CLRenderInformationBase()
{
  CRootContainer::getKeyFactory()->remove(this->mKey);
}

/**
 * Returns the id of the referenced render information object..
 */
const std::string& CLRenderInformationBase::getReferenceRenderInformationKey() const
{
  return this->mReferenceRenderInformation;
}

/**
 * Sets the id of the referenced render information object.
 */
void CLRenderInformationBase::setReferenceRenderInformationKey(const std::string& key)
{
  this->mReferenceRenderInformation = key;
}

/**
 * Returns the number of color definitions.
 */
size_t CLRenderInformationBase::getNumColorDefinitions() const
{
  return this->mListOfColorDefinitions.size();
}

/**
 * Returns a pointer to the list of color definitions.
 */
CDataVector<CLColorDefinition>* CLRenderInformationBase::getListOfColorDefinitions()
{
  return &(this->mListOfColorDefinitions);
}

/**
 * Returns a const pointer to the list of color definitions.
 */
const CDataVector<CLColorDefinition>* CLRenderInformationBase::getListOfColorDefinitions() const
{
  return &(this->mListOfColorDefinitions);
}

/**
 * Returns a pointer to the color definition with the given index, or NULL
 *if the index is invalid.
 */
CLColorDefinition* CLRenderInformationBase::getColorDefinition(size_t index)
{
  return (index < this->mListOfColorDefinitions.size()) ? &this->mListOfColorDefinitions[index] : NULL;
}

/**
 * Returns a const pointer to the color definition with the given index, or NULL
 *if the index is invalid.
 */
const CLColorDefinition* CLRenderInformationBase::getColorDefinition(size_t index) const
{
  return (index < this->mListOfColorDefinitions.size()) ? &this->mListOfColorDefinitions[index] : NULL;
}

/**
 * Creates a new color definition.
 */
CLColorDefinition* CLRenderInformationBase::createColorDefinition()
{
  CLColorDefinition* pCD = new CLColorDefinition();
  this->mListOfColorDefinitions.add(pCD, true);
  return pCD;
}

/**
 * Removes the color definition with the given index.
 */
void CLRenderInformationBase::removeColorDefinition(size_t index)
{
  if (index < this->mListOfColorDefinitions.size())
    {
      this->mListOfColorDefinitions.remove(index);
    }
}

/**
 * Adds a copy of the given color definition to the end of the list of
 * color definitions.
 */
void CLRenderInformationBase::addColorDefinition(const CLColorDefinition* pCD)
{
  this->mListOfColorDefinitions.add(new CLColorDefinition(*pCD), true);
}

/**
 * Returns the number of gradient definitions.
 */
size_t CLRenderInformationBase::getNumGradientDefinitions() const
{
  return this->mListOfGradientDefinitions.size();
}

/**
 * Returns a pointer to the list of gradient definitions.
 */
CDataVector<CLGradientBase>* CLRenderInformationBase::getListOfGradientDefinitions()
{
  return &(this->mListOfGradientDefinitions);
}

/**
 * Returns a const pointer to the list of gradient definitions.
 */
const CDataVector<CLGradientBase>* CLRenderInformationBase::getListOfGradientDefinitions() const
{
  return &(this->mListOfGradientDefinitions);
}

/**
 * Returns a pointer to the gradient definition with the given index, or NULL
 *if the index is invalid.
 */
CLGradientBase* CLRenderInformationBase::getGradientDefinition(size_t index)
{
  return (index < this->mListOfGradientDefinitions.size()) ? &this->mListOfGradientDefinitions[index] : NULL;
}

/**
 * Returns a const pointer to the gradient definition with the given index, or NULL
 *if the index is invalid.
 */
const CLGradientBase* CLRenderInformationBase::getGradientDefinition(size_t index) const
{
  return (index < this->mListOfGradientDefinitions.size()) ? &this->mListOfGradientDefinitions[index] : NULL;
}

/**
 * Creates a new radial gradient definition.
 */
CLRadialGradient* CLRenderInformationBase::createRadialGradientDefinition()
{
  CLRadialGradient* pRG = new CLRadialGradient();
  this->mListOfGradientDefinitions.add(pRG, true);
  return pRG;
}

/**
 * Creates a new linear gradient definition.
 */
CLLinearGradient* CLRenderInformationBase::createLinearGradientDefinition()
{
  CLLinearGradient* pLG = new CLLinearGradient();
  this->mListOfGradientDefinitions.add(pLG, true);
  return pLG;
}

/**
 * Removes the gradient definition with the given index.
 */
void CLRenderInformationBase::removeGradientDefinition(size_t index)
{
  if (index < this->mListOfGradientDefinitions.size())
    {
      this->mListOfGradientDefinitions.remove(index);
    }
}

/**
 * Adds a copy of the given gradient definition to the end of the list of
 * gradient definitions.
 */
void CLRenderInformationBase::addGradientDefinition(const CLGradientBase* pGradient)
{
  if (dynamic_cast<const CLLinearGradient*>(pGradient))
    {
      this->mListOfGradientDefinitions.add(new CLLinearGradient(*static_cast<const CLLinearGradient*>(pGradient)), true);
    }
  else if (dynamic_cast<const CLRadialGradient*>(pGradient))
    {
      this->mListOfGradientDefinitions.add(new CLRadialGradient(*static_cast<const CLRadialGradient*>(pGradient)), true);
    }
}

/**
 * Returns the number of line endings.
 */
size_t CLRenderInformationBase::getNumLineEndings() const
{
  return this->mListOfLineEndings.size();
}

/**
 * Returns a pointer to the list of line endings.
 */
CDataVector<CLLineEnding>* CLRenderInformationBase::getListOfLineEndings()
{
  return &(this->mListOfLineEndings);
}

/**
 * Returns a const pointer to the list of line endings.
 */
const CDataVector<CLLineEnding>* CLRenderInformationBase::getListOfLineEndings() const
{
  return &(this->mListOfLineEndings);
}

/**
 * Returns a pointer to the line ending with the given index, or NULL
 *if the index is invalid.
 */
CLLineEnding* CLRenderInformationBase::getLineEnding(size_t index)
{
  return (index < this->mListOfLineEndings.size()) ? &this->mListOfLineEndings[index] : NULL;
}

/**
 * Returns a const pointer to the line ending with the given index, or NULL
 *if the index is invalid.
 */
const CLLineEnding* CLRenderInformationBase::getLineEnding(size_t index) const
{
  return (index < this->mListOfLineEndings.size()) ? &this->mListOfLineEndings[index] : NULL;
}

/**
 * Creates a new line ending.
 */
CLLineEnding* CLRenderInformationBase::createLineEnding()
{
  CLLineEnding* pLE = new CLLineEnding();
  this->mListOfLineEndings.add(pLE, true);
  return pLE;
}

/**
 * Removes the line ending with the given index.
 */
void CLRenderInformationBase::removeLineEnding(size_t index)
{
  if (index < this->mListOfLineEndings.size())
    {
      this->mListOfLineEndings.remove(index);
    }
}

/**
 * Adds a copy of the given line ending to the end of the list of line
 *endings.
 */
void CLRenderInformationBase::addLineEnding(const CLLineEnding* pLE)
{
  this->mListOfLineEndings.add(new CLLineEnding(*pLE), true);
}

const std::string& CLRenderInformationBase::getBackgroundColor() const
{
  return mBackgroundColor;
}

void CLRenderInformationBase::setBackgroundColor(const std::string& bg)
{
  this->mBackgroundColor = bg;
}

/**
 * Returns the key of the color definition.
 */
const std::string& CLRenderInformationBase::getKey() const
{
  return this->mKey;
}

/**
 * Adds the attributes for a graphical primitive 1D object to the passed in.
 * object.
 */
void CLRenderInformationBase::addSBMLAttributes(RenderInformationBase* pBase
    /*
        ,std::map<std::string,std::string>& colorKeyToIdMap
        ,std::map<std::string,std::string>& gradientKeyToIdMap
        ,std::map<std::string,std::string>& lineEndingKeyToIdMap
    */
                                               ) const
{
  pBase->setReferenceRenderInformationId(this->getReferenceRenderInformationKey());
  pBase->setBackgroundColor(this->getBackgroundColor());
  pBase->setId(getKey());

  if (!mName.empty())
    {
      pBase->setName(mName);
    }

  size_t i, iMax = this->mListOfColorDefinitions.size();
  int result;

  unsigned int level = pBase->getLevel();
  unsigned int version = pBase->getVersion();

  for (i = 0; i < iMax; ++i)
    {
      ColorDefinition* pCD = this->getColorDefinition(i)->toSBML(level, version);
      result = pBase->addColorDefinition(pCD);
      assert(result == LIBSBML_OPERATION_SUCCESS);
      //colorKeyToIdMap.insert(std::pair<std::string,std::string>(this->getColorDefinition(i)->getKey(),pCD->getId()));
      delete pCD;
    }

  iMax = this->mListOfGradientDefinitions.size();
  GradientBase* pGB = NULL;
  const CLGradientBase* pLGB = NULL;

  for (i = 0; i < iMax; ++i)
    {
      pLGB = this->getGradientDefinition(i);

      if (dynamic_cast<const CLRadialGradient*>(pLGB))
        {
          pGB = static_cast<const CLRadialGradient*>(pLGB)->toSBML(level, version);
        }
      else
        {
          pGB = static_cast<const CLLinearGradient*>(pLGB)->toSBML(level, version);
        }

      result = pBase->addGradientDefinition(pGB);
      assert(result == LIBSBML_OPERATION_SUCCESS);
      //gradientKeyToIdMap.insert(std::pair<std::string,std::string>(pLGB->getKey(),pGB->getId()));
      delete pGB;
    }

  iMax = this->mListOfLineEndings.size();

  for (i = 0; i < iMax; ++i)
    {
      const CLLineEnding* lineEnding = this->getLineEnding(i);
      LineEnding* pLE = lineEnding->toSBML(level, version);
      result = pBase->addLineEnding(pLE);
      assert(result == LIBSBML_OPERATION_SUCCESS);
      //lineEndingKeyToIdMap.insert(std::pair<std::string,std::string>(this->getLineEnding(i)->getKey(),pLE->getId()));
      delete pLE;
    }
}

/**
 * Sets the name of the object.
 */
void CLRenderInformationBase::setName(const std::string& name)
{
  this->mName = name;
}

/**
 * Returns the name of the object.
 */
const std::string& CLRenderInformationBase::getName() const
{
  return this->mName;
}
<commit_msg>- issue 2572: create a bounding box when none exists before reading<commit_after>// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#define USE_LAYOUT 1
#define USE_RENDER 1

#include <sbml/packages/render/sbml/RenderInformationBase.h>
#include <sbml/packages/render/sbml/ColorDefinition.h>
#include <sbml/packages/render/sbml/GradientBase.h>
#include <sbml/packages/render/sbml/LinearGradient.h>
#include <sbml/packages/render/sbml/RadialGradient.h>
#include <sbml/packages/render/sbml/LineEnding.h>

#include "CLRenderInformationBase.h"
#include "CLGradientBase.h"
#include "CLLinearGradient.h"
#include "CLRadialGradient.h"

#include "copasi/core/CRootContainer.h"
#include "copasi/report/CKeyFactory.h"

/**
 * Constructor.
 */
CLRenderInformationBase::CLRenderInformationBase(const std::string& name, CDataContainer* pParent):
  CLBase(),
  CDataContainer(name, pParent),
  mKey(""),
  mName("")
{
}

/**
 * Copy constructor.
 */
CLRenderInformationBase::CLRenderInformationBase(const CLRenderInformationBase& source, CDataContainer* pParent):
  CLBase(source),
  CDataContainer(source, pParent),
  mReferenceRenderInformation(source.mReferenceRenderInformation),
  mBackgroundColor(source.mBackgroundColor),
  mListOfColorDefinitions(source.mListOfColorDefinitions, this),
  mListOfGradientDefinitions(source.mListOfGradientDefinitions, this),
  mListOfLineEndings(source.mListOfLineEndings, this),
  mKey(""),
  mName(source.mName)
{
}

/**
 * Constructor to generate object from the corresponding SBML object.
 */
CLRenderInformationBase::CLRenderInformationBase(const RenderInformationBase& source,
    const std::string& name,
    /*
    std::map<std::string,std::string>& colorIdToKeyMap,
    std::map<std::string,std::string>& gradientIdToKeyMap,
    std::map<std::string,std::string>& lineEndingIdToKeyMap,
    */
    CDataContainer* pParent):

  CLBase(),
  CDataContainer(name, pParent),
  mReferenceRenderInformation(source.getReferenceRenderInformationId()),
  mBackgroundColor(source.getBackgroundColor()),
  mKey(""),
  mName(source.getName())
{
  size_t i, iMax = source.getNumColorDefinitions();
  const ColorDefinition* pCD = NULL;
  CLColorDefinition* pLCD = NULL;

  for (i = 0; i < iMax; ++i)
    {
      pCD = source.getColorDefinition((unsigned int) i);
      pLCD = new CLColorDefinition(*pCD);
      this->mListOfColorDefinitions.add(pLCD, true);
      //colorIdToKeyMap.insert(std::pair<std::string,std::string>(pCD->getId(),pLCD->getKey()));
    }

  const GradientBase* pGD = NULL;

  CLGradientBase* pLGD = NULL;

  iMax = source.getNumGradientDefinitions();

  for (i = 0; i < iMax; ++i)
    {
      pGD = source.getGradientDefinition((unsigned int) i);

      if (dynamic_cast<const LinearGradient*>(pGD))
        {
          pLGD = new CLLinearGradient(*static_cast<const LinearGradient*>(pGD));
          this->mListOfGradientDefinitions.add(pLGD, true);
        }
      else if (dynamic_cast<const RadialGradient*>(source.getGradientDefinition((unsigned int) i)))
        {
          pLGD = new CLRadialGradient(*static_cast<const RadialGradient*>(pGD));
          this->mListOfGradientDefinitions.add(pLGD, true);
        }

      //gradientIdToKeyMap.insert(std::pair<std::string,std::string>(pGD->getId(),pLGD->getKey()));
    }

  const LineEnding* pLE = NULL;

  CLLineEnding* pLLE = NULL;

  iMax = source.getNumLineEndings();

  for (i = 0; i < iMax; ++i)
    {
      pLE = source.getLineEnding((unsigned int) i);
#if LIBSBML_VERSION  > 51600

      if (!pLE->isSetBoundingBox())
        const_cast<LineEnding*>(pLE)->createBoundingBox();

#endif
      pLLE = new CLLineEnding(*pLE);
      this->mListOfLineEndings.add(pLLE, true);
      //lineEndingIdToKeyMap.insert(std::pair<std::string,std::string>(pLE->getId(),pLLE->getKey()));
    }
}

/**
 * Destructor
 */
CLRenderInformationBase::~CLRenderInformationBase()
{
  CRootContainer::getKeyFactory()->remove(this->mKey);
}

/**
 * Returns the id of the referenced render information object..
 */
const std::string& CLRenderInformationBase::getReferenceRenderInformationKey() const
{
  return this->mReferenceRenderInformation;
}

/**
 * Sets the id of the referenced render information object.
 */
void CLRenderInformationBase::setReferenceRenderInformationKey(const std::string& key)
{
  this->mReferenceRenderInformation = key;
}

/**
 * Returns the number of color definitions.
 */
size_t CLRenderInformationBase::getNumColorDefinitions() const
{
  return this->mListOfColorDefinitions.size();
}

/**
 * Returns a pointer to the list of color definitions.
 */
CDataVector<CLColorDefinition>* CLRenderInformationBase::getListOfColorDefinitions()
{
  return &(this->mListOfColorDefinitions);
}

/**
 * Returns a const pointer to the list of color definitions.
 */
const CDataVector<CLColorDefinition>* CLRenderInformationBase::getListOfColorDefinitions() const
{
  return &(this->mListOfColorDefinitions);
}

/**
 * Returns a pointer to the color definition with the given index, or NULL
 *if the index is invalid.
 */
CLColorDefinition* CLRenderInformationBase::getColorDefinition(size_t index)
{
  return (index < this->mListOfColorDefinitions.size()) ? &this->mListOfColorDefinitions[index] : NULL;
}

/**
 * Returns a const pointer to the color definition with the given index, or NULL
 *if the index is invalid.
 */
const CLColorDefinition* CLRenderInformationBase::getColorDefinition(size_t index) const
{
  return (index < this->mListOfColorDefinitions.size()) ? &this->mListOfColorDefinitions[index] : NULL;
}

/**
 * Creates a new color definition.
 */
CLColorDefinition* CLRenderInformationBase::createColorDefinition()
{
  CLColorDefinition* pCD = new CLColorDefinition();
  this->mListOfColorDefinitions.add(pCD, true);
  return pCD;
}

/**
 * Removes the color definition with the given index.
 */
void CLRenderInformationBase::removeColorDefinition(size_t index)
{
  if (index < this->mListOfColorDefinitions.size())
    {
      this->mListOfColorDefinitions.remove(index);
    }
}

/**
 * Adds a copy of the given color definition to the end of the list of
 * color definitions.
 */
void CLRenderInformationBase::addColorDefinition(const CLColorDefinition* pCD)
{
  this->mListOfColorDefinitions.add(new CLColorDefinition(*pCD), true);
}

/**
 * Returns the number of gradient definitions.
 */
size_t CLRenderInformationBase::getNumGradientDefinitions() const
{
  return this->mListOfGradientDefinitions.size();
}

/**
 * Returns a pointer to the list of gradient definitions.
 */
CDataVector<CLGradientBase>* CLRenderInformationBase::getListOfGradientDefinitions()
{
  return &(this->mListOfGradientDefinitions);
}

/**
 * Returns a const pointer to the list of gradient definitions.
 */
const CDataVector<CLGradientBase>* CLRenderInformationBase::getListOfGradientDefinitions() const
{
  return &(this->mListOfGradientDefinitions);
}

/**
 * Returns a pointer to the gradient definition with the given index, or NULL
 *if the index is invalid.
 */
CLGradientBase* CLRenderInformationBase::getGradientDefinition(size_t index)
{
  return (index < this->mListOfGradientDefinitions.size()) ? &this->mListOfGradientDefinitions[index] : NULL;
}

/**
 * Returns a const pointer to the gradient definition with the given index, or NULL
 *if the index is invalid.
 */
const CLGradientBase* CLRenderInformationBase::getGradientDefinition(size_t index) const
{
  return (index < this->mListOfGradientDefinitions.size()) ? &this->mListOfGradientDefinitions[index] : NULL;
}

/**
 * Creates a new radial gradient definition.
 */
CLRadialGradient* CLRenderInformationBase::createRadialGradientDefinition()
{
  CLRadialGradient* pRG = new CLRadialGradient();
  this->mListOfGradientDefinitions.add(pRG, true);
  return pRG;
}

/**
 * Creates a new linear gradient definition.
 */
CLLinearGradient* CLRenderInformationBase::createLinearGradientDefinition()
{
  CLLinearGradient* pLG = new CLLinearGradient();
  this->mListOfGradientDefinitions.add(pLG, true);
  return pLG;
}

/**
 * Removes the gradient definition with the given index.
 */
void CLRenderInformationBase::removeGradientDefinition(size_t index)
{
  if (index < this->mListOfGradientDefinitions.size())
    {
      this->mListOfGradientDefinitions.remove(index);
    }
}

/**
 * Adds a copy of the given gradient definition to the end of the list of
 * gradient definitions.
 */
void CLRenderInformationBase::addGradientDefinition(const CLGradientBase* pGradient)
{
  if (dynamic_cast<const CLLinearGradient*>(pGradient))
    {
      this->mListOfGradientDefinitions.add(new CLLinearGradient(*static_cast<const CLLinearGradient*>(pGradient)), true);
    }
  else if (dynamic_cast<const CLRadialGradient*>(pGradient))
    {
      this->mListOfGradientDefinitions.add(new CLRadialGradient(*static_cast<const CLRadialGradient*>(pGradient)), true);
    }
}

/**
 * Returns the number of line endings.
 */
size_t CLRenderInformationBase::getNumLineEndings() const
{
  return this->mListOfLineEndings.size();
}

/**
 * Returns a pointer to the list of line endings.
 */
CDataVector<CLLineEnding>* CLRenderInformationBase::getListOfLineEndings()
{
  return &(this->mListOfLineEndings);
}

/**
 * Returns a const pointer to the list of line endings.
 */
const CDataVector<CLLineEnding>* CLRenderInformationBase::getListOfLineEndings() const
{
  return &(this->mListOfLineEndings);
}

/**
 * Returns a pointer to the line ending with the given index, or NULL
 *if the index is invalid.
 */
CLLineEnding* CLRenderInformationBase::getLineEnding(size_t index)
{
  return (index < this->mListOfLineEndings.size()) ? &this->mListOfLineEndings[index] : NULL;
}

/**
 * Returns a const pointer to the line ending with the given index, or NULL
 *if the index is invalid.
 */
const CLLineEnding* CLRenderInformationBase::getLineEnding(size_t index) const
{
  return (index < this->mListOfLineEndings.size()) ? &this->mListOfLineEndings[index] : NULL;
}

/**
 * Creates a new line ending.
 */
CLLineEnding* CLRenderInformationBase::createLineEnding()
{
  CLLineEnding* pLE = new CLLineEnding();
  this->mListOfLineEndings.add(pLE, true);
  return pLE;
}

/**
 * Removes the line ending with the given index.
 */
void CLRenderInformationBase::removeLineEnding(size_t index)
{
  if (index < this->mListOfLineEndings.size())
    {
      this->mListOfLineEndings.remove(index);
    }
}

/**
 * Adds a copy of the given line ending to the end of the list of line
 *endings.
 */
void CLRenderInformationBase::addLineEnding(const CLLineEnding* pLE)
{
  this->mListOfLineEndings.add(new CLLineEnding(*pLE), true);
}

const std::string& CLRenderInformationBase::getBackgroundColor() const
{
  return mBackgroundColor;
}

void CLRenderInformationBase::setBackgroundColor(const std::string& bg)
{
  this->mBackgroundColor = bg;
}

/**
 * Returns the key of the color definition.
 */
const std::string& CLRenderInformationBase::getKey() const
{
  return this->mKey;
}

/**
 * Adds the attributes for a graphical primitive 1D object to the passed in.
 * object.
 */
void CLRenderInformationBase::addSBMLAttributes(RenderInformationBase* pBase
    /*
        ,std::map<std::string,std::string>& colorKeyToIdMap
        ,std::map<std::string,std::string>& gradientKeyToIdMap
        ,std::map<std::string,std::string>& lineEndingKeyToIdMap
    */
                                               ) const
{
  pBase->setReferenceRenderInformationId(this->getReferenceRenderInformationKey());
  pBase->setBackgroundColor(this->getBackgroundColor());
  pBase->setId(getKey());

  if (!mName.empty())
    {
      pBase->setName(mName);
    }

  size_t i, iMax = this->mListOfColorDefinitions.size();
  int result;

  unsigned int level = pBase->getLevel();
  unsigned int version = pBase->getVersion();

  for (i = 0; i < iMax; ++i)
    {
      ColorDefinition* pCD = this->getColorDefinition(i)->toSBML(level, version);
      result = pBase->addColorDefinition(pCD);
      assert(result == LIBSBML_OPERATION_SUCCESS);
      //colorKeyToIdMap.insert(std::pair<std::string,std::string>(this->getColorDefinition(i)->getKey(),pCD->getId()));
      delete pCD;
    }

  iMax = this->mListOfGradientDefinitions.size();
  GradientBase* pGB = NULL;
  const CLGradientBase* pLGB = NULL;

  for (i = 0; i < iMax; ++i)
    {
      pLGB = this->getGradientDefinition(i);

      if (dynamic_cast<const CLRadialGradient*>(pLGB))
        {
          pGB = static_cast<const CLRadialGradient*>(pLGB)->toSBML(level, version);
        }
      else
        {
          pGB = static_cast<const CLLinearGradient*>(pLGB)->toSBML(level, version);
        }

      result = pBase->addGradientDefinition(pGB);
      assert(result == LIBSBML_OPERATION_SUCCESS);
      //gradientKeyToIdMap.insert(std::pair<std::string,std::string>(pLGB->getKey(),pGB->getId()));
      delete pGB;
    }

  iMax = this->mListOfLineEndings.size();

  for (i = 0; i < iMax; ++i)
    {
      const CLLineEnding* lineEnding = this->getLineEnding(i);
      LineEnding* pLE = lineEnding->toSBML(level, version);
      result = pBase->addLineEnding(pLE);
      assert(result == LIBSBML_OPERATION_SUCCESS);
      //lineEndingKeyToIdMap.insert(std::pair<std::string,std::string>(this->getLineEnding(i)->getKey(),pLE->getId()));
      delete pLE;
    }
}

/**
 * Sets the name of the object.
 */
void CLRenderInformationBase::setName(const std::string& name)
{
  this->mName = name;
}

/**
 * Returns the name of the object.
 */
const std::string& CLRenderInformationBase::getName() const
{
  return this->mName;
}
<|endoftext|>


<commit_before>#include "renderer-pre.hpp"

namespace col {

	PixFont FontTiny;

	using ResMap = std::unordered_map<ResKey, Texture>;

	ResMap res_map;

	ResKey make_reskey(ResCat cat, ResNum num) {
		return (ResKey(cat) << 16) | ResKey(num);
	}

	ResCat get_rescat(ResKey k) {
		return k >> 16;
	}

	ResNum get_resnum(ResKey k) {
		return (k << 16) >> 16;
	}

	Path get_res_dir(ResCat cat) {
		// categories, *xxx* -- generated to memory image
		switch (cat) {
			case TERR: return "TERRAIN_SS";
			case ICON: return "ICONS_SS";
			case PHYS: return "PHYS0_SS";
			case ARCH: return "PARCH_SS";
			case COLONY: return "COLONY_PIK";
			case BUILD: return "BUILDING_SS";
			case WOODTILE: return "WOODTILE_SS";
			case DIFFUSE: return "*DIFFUSE*";
			case COAST: return "*COAST*";
			case ZZ: return "ZZ";
		}
		fail("unknown resource category: %||\n", cat);
	}

	Path get_res_path(ResCat cat, ResNum num) {
		return conf.tile_path / get_res_dir(cat) / format("%|03|.png", num);
	}

	Path get_res_path_key(ResKey key) {
		return get_res_path(get_rescat(key), get_resnum(key));
	}

	// Get resource from global cache (load on demand)
	Texture const& res(Front & fr, ResCat cat, ResNum num)
	{
		auto key = make_reskey(cat, num);
		auto p = res_map.find(key);
		if (p != res_map.end()) {
			return (*p).second;
		}
		else {
			auto path = get_res_path(cat, num);
			auto & img = res_map[key];
			img = fr.make_texture(path);
			return img;
		}
	}

	void preload(ResCat cat, ResNum num, Texture && tex) {
		auto key = make_reskey(cat, num);
		res_map[key] = std::move(tex);
	}

	Image replace_black(Image const& inn, Image const& tex, v2s toff) {
		/* Create new surface

		mask colors meaning:
		 black -> take from tex
		 else -> take from mask

		 toff -- tex offset vector

		*/

		//print("replace_black: %|| + %|| <- %||\n", inn.dim, toff, tex.dim);

		auto dim = inn.get_dim();
		auto out = Image(dim);

		for (int j = 0; j < dim[1]; ++j) {
			for (int i = 0; i < dim[0]; ++i) {
				auto c = inn({i,j});
				auto pos = v2s(i,j);

				//print("c = %||\n", c);

				if (c.a == 0) {
					out(pos) = Color(0,0,0,0);
				}
				else if (c == Color(0,0,0,255)) {

					out(pos) = tex(toff + pos);
				}
				else {
					out(pos) = inn(pos);
				}

			}
		}

		return out;
	}

	//void render_fields(Front &win, Env const& env, Console const& con,
	//	v2s pix, Coords const& pos);

	v2s get_loffset(int l) {
		switch(l){
			case 0: return v2s(0,0) * ly.scale;
			case 1: return v2s(8,0) * ly.scale;
			case 2: return v2s(8,8) * ly.scale;
			case 3: return v2s(0,8) * ly.scale;
		}
		fail("invalid 'l'");
	}

	Texture make_combined_texture(
		Front & fr,
		std::pair<ResCat, ResNum> p,
		std::pair<ResCat, ResNum> b,
		v2s off
	) {
		auto p_img = front::load_png(
			get_res_path(p.first, p.second)
		);

		auto b_img = front::load_png(
			get_res_path(b.first, b.second)
		);

		auto surf = replace_black(p_img, b_img, off);

		return fr.make_texture(surf);
	}

	void preload_coast(Front & fr, Biome bio, int start) {
		for (int k = 0; k < 8; ++k) {
			for (int l = 0; l < 4; ++l) {
				int ind = (k<<2) + l;

				preload(COAST, start + ind,
					make_combined_texture(fr,
						{PHYS, 109+ind},
						{TERR, bio},
						get_loffset(l)
					)
				);
			}
		}
	}

	int const TextureOceanId = 11;
	int const TextureSeaLaneId = 11;

	void preload_coast(Front & back) {
		// 109 - 140

		preload_coast(back, TextureOceanId, 0);
		preload_coast(back, TextureSeaLaneId, 50);
	}

	void preload_terrain(Front & fr) {
		for (int i=1; i<13; ++i) {
			preload(DIFFUSE,  0+i,
				make_combined_texture(fr, {PHYS, 105}, {TERR, i}, {0,0})
			);
			preload(DIFFUSE, 50+i,
				make_combined_texture(fr, {PHYS, 106}, {TERR, i}, {0,0})
			);
			preload(DIFFUSE, 100+i,
				make_combined_texture(fr, {PHYS, 107}, {TERR, i}, {0,0})
			);
			preload(DIFFUSE, 150+i,
				make_combined_texture(fr, {PHYS, 108}, {TERR, i}, {0,0})
			);
		}

		preload_coast(fr);
	}

	void preload_renderer(Front & fr) {
		preload_terrain(fr);
		FontTiny.load(fr, conf.font_tiny_path, -1 * ly.scale);
	}

}
<commit_msg>preload<commit_after>#include "renderer-pre.hpp"

namespace col {

	PixFont FontTiny;

	using ResMap = std::unordered_map<ResKey, Texture>;

	ResMap res_map;

	ResKey make_reskey(ResCat cat, ResNum num) {
		return (ResKey(cat) << 16) | ResKey(num);
	}

	ResCat get_rescat(ResKey k) {
		return k >> 16;
	}

	ResNum get_resnum(ResKey k) {
		return (k << 16) >> 16;
	}

	Path get_res_dir(ResCat cat) {
		// categories, *xxx* -- generated to memory image
		switch (cat) {
			case TERR: return "TERRAIN_SS";
			case ICON: return "ICONS_SS";
			case PHYS: return "PHYS0_SS";
			case ARCH: return "PARCH_SS";
			case COLONY: return "COLONY_PIK";
			case BUILD: return "BUILDING_SS";
			case WOODTILE: return "WOODTILE_SS";
			case DIFFUSE: return "*DIFFUSE*";
			case COAST: return "*COAST*";
			case ZZ: return "ZZ";
		}
		fail("unknown resource category: %||\n", cat);
	}

	Path get_res_path(ResCat cat, ResNum num) {
		return conf.tile_path / get_res_dir(cat) / format("%|03|.png", num);
	}

	Path get_res_path_key(ResKey key) {
		return get_res_path(get_rescat(key), get_resnum(key));
	}

	// Get resource from global cache (load on demand)
	Texture const& res(Front & fr, ResCat cat, ResNum num)
	{
		//print("res %|d| %|d|\n", cat, num);

		auto key = make_reskey(cat, num);
		auto p = res_map.find(key);
		if (p != res_map.end()) {
			return (*p).second;
		}
		else {
			auto path = get_res_path(cat, num);
			auto & img = res_map[key];
			img = fr.make_texture(path);
			return img;
		}
	}

	void preload(ResCat cat, ResNum num, Texture && tex) {
		auto key = make_reskey(cat, num);
		res_map[key] = std::move(tex);
	}

	Image replace_black(Image const& inn, Image const& tex, v2s toff) {
		/* Create new surface

		mask colors meaning:
		 black -> take from tex
		 else -> take from mask

		 toff -- tex offset vector

		*/

		//print("replace_black: %|| + %|| <- %||\n", inn.dim, toff, tex.dim);

		auto dim = inn.get_dim();
		auto out = Image(dim);

		for (int16_t j = 0; j < dim[1]; ++j) {
			for (int16_t i = 0; i < dim[0]; ++i) {
				auto c = inn({i,j});
				auto pos = v2s(i,j);

				//print("c = %||\n", c);

				if (c.a == 0) {
					out(pos) = Color(0,0,0,0);
				}
				else if (c == Color(0,0,0,255)) {

					out(pos) = tex(toff + pos);
				}
				else {
					out(pos) = inn(pos);
				}

			}
		}

		return out;
	}

	//void render_fields(Front &win, Env const& env, Console const& con,
	//	v2s pix, Coords const& pos);

	v2s get_loffset(int l) {
		switch(l){
			case 0: return v2s(0,0) * ly.scale;
			case 1: return v2s(8,0) * ly.scale;
			case 2: return v2s(8,8) * ly.scale;
			case 3: return v2s(0,8) * ly.scale;
		}
		fail("invalid 'l'");
	}

	Texture make_combined_texture(
		Front & fr,
		std::pair<ResCat, ResNum> p,
		std::pair<ResCat, ResNum> b,
		v2s off
	) {
		auto p_img = front::load_png(
			get_res_path(p.first, p.second)
		);

		auto b_img = front::load_png(
			get_res_path(b.first, b.second)
		);

		auto surf = replace_black(p_img, b_img, off);

		return fr.make_texture(surf);
	}

	void preload_coast(Front & fr, Biome bio, int start) {
		for (int k = 0; k < 8; ++k) {
			for (int l = 0; l < 4; ++l) {
				int ind = (k<<2) + l;

				preload(COAST, start + ind,
					make_combined_texture(fr,
						{PHYS, 109+ind},
						{TERR, bio},
						get_loffset(l)
					)
				);
			}
		}
	}

	int const TextureOceanId = 11;
	int const TextureSeaLaneId = 11;

	void preload_coast(Front & back) {
		// 109 - 140

		preload_coast(back, TextureOceanId, 0);
		preload_coast(back, TextureSeaLaneId, 50);
	}

	void preload_terrain(Front & fr) {
		for (int i=1; i<13; ++i) {

			// TODO: skip if file not exists
			if (i == 9 or i == 12) {
				continue;
			}

			preload(DIFFUSE,  0+i,
				make_combined_texture(fr, {PHYS, 105}, {TERR, i}, {0,0})
			);
			preload(DIFFUSE, 50+i,
				make_combined_texture(fr, {PHYS, 106}, {TERR, i}, {0,0})
			);
			preload(DIFFUSE, 100+i,
				make_combined_texture(fr, {PHYS, 107}, {TERR, i}, {0,0})
			);
			preload(DIFFUSE, 150+i,
				make_combined_texture(fr, {PHYS, 108}, {TERR, i}, {0,0})
			);
		}

		preload_coast(fr);
	}

	void preload_renderer(Front & fr) {
		preload_terrain(fr);
		FontTiny.load(fr, conf.font_tiny_path, -1 * ly.scale);
	}

}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMLoadImplementationsRegister.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.

     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.

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

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkVisitorDispatcher.h"

#include "itkFEMLoadPoint.h"
#include "itkFEMLoadGrav.h"
#include "itkFEMLoadEdge.h"
#include "itkFEMLoadLandmark.h"

#include "itkFEMLoadImplementationGenericBodyLoad.h"
#include "itkFEMLoadImplementationGenericLandmarkLoad.h"

#include "itkFEMElement2DC0LinearLineStress.h"
#include "itkFEMElement2DC1Beam.h"
#include "itkFEMElement2DC0LinearTriangularStress.h"
#include "itkFEMElement2DC0LinearQuadrilateralStress.h"
#include "itkFEMElement2DC0LinearQuadrilateralMembrane.h"
#include "itkFEMElement3DC0LinearTetrahedronStrain.h"
#include "itkFEMElement3DC0LinearHexahedronStrain.h"

namespace itk {
namespace fem {

/* This macro makes registering Load implementations easier. */
#define REGISTER_LOAD_EX(ElementClass,LoadClass,FunctionName) \
  VisitorDispatcher<ElementClass, ElementClass::LoadType, ElementClass::LoadImplementationFunctionPointer> \
  ::RegisterVisitor((LoadClass*)0, &FunctionName);
/* Use this macro to also automatically declare load implementation function. */
#define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \
  extern void FunctionName(ElementClass::ConstPointer, ElementClass::LoadPointer, ElementClass::VectorType& ); \
  REGISTER_LOAD_EX(ElementClass,LoadClass,FunctionName)

/**
 * Registers all Load classes in the FEM library with VisitorDispatcher.
 * This function must be called before the FEM library is functional!.
 */
void LoadImplementationsRegister(void)
{

  // Loads acting on LineStress element
  REGISTER_LOAD_EX(Element2DC0LinearLineStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);

  // Loads acting on Beam element
  REGISTER_LOAD_EX(Element2DC1Beam,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);

  // Loads acting on QuadrilateralStress element
  REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralStress,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on QuadrilateralMembrane element
  REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on TriangularStress element
  REGISTER_LOAD_EX(Element2DC0LinearTriangularStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element2DC0LinearTriangularStress,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on HexahedronStrain element
  REGISTER_LOAD_EX(Element3DC0LinearHexahedronStrain,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element3DC0LinearHexahedronStrain,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on TetrahedronStrain element
  REGISTER_LOAD_EX(Element3DC0LinearTetrahedronStrain,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element3DC0LinearTetrahedronStrain,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Add any additional loads here in a similar fashion...
  // Make sure that the pointer to the visit function is the correct one!!!

}

}} // end namespace itk::fem
<commit_msg>adding new membrane elements to cmakelists<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMLoadImplementationsRegister.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.

     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.

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

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkVisitorDispatcher.h"

#include "itkFEMLoadPoint.h"
#include "itkFEMLoadGrav.h"
#include "itkFEMLoadEdge.h"
#include "itkFEMLoadLandmark.h"

#include "itkFEMLoadImplementationGenericBodyLoad.h"
#include "itkFEMLoadImplementationGenericLandmarkLoad.h"

#include "itkFEMElement2DC0LinearLineStress.h"
#include "itkFEMElement2DC1Beam.h"
#include "itkFEMElement2DC0LinearTriangularStress.h"
#include "itkFEMElement2DC0LinearTriangularMembrane.h"
#include "itkFEMElement2DC0LinearQuadrilateralStress.h"
#include "itkFEMElement2DC0LinearQuadrilateralMembrane.h"
#include "itkFEMElement3DC0LinearTetrahedronStrain.h"
#include "itkFEMElement3DC0LinearHexahedronStrain.h"
#include "itkFEMElement3DC0LinearTetrahedronMembrane.h"
#include "itkFEMElement3DC0LinearHexahedronMembrane.h"

namespace itk {
namespace fem {

/* This macro makes registering Load implementations easier. */
#define REGISTER_LOAD_EX(ElementClass,LoadClass,FunctionName) \
  VisitorDispatcher<ElementClass, ElementClass::LoadType, ElementClass::LoadImplementationFunctionPointer> \
  ::RegisterVisitor((LoadClass*)0, &FunctionName);
/* Use this macro to also automatically declare load implementation function. */
#define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \
  extern void FunctionName(ElementClass::ConstPointer, ElementClass::LoadPointer, ElementClass::VectorType& ); \
  REGISTER_LOAD_EX(ElementClass,LoadClass,FunctionName)

/**
 * Registers all Load classes in the FEM library with VisitorDispatcher.
 * This function must be called before the FEM library is functional!.
 */
void LoadImplementationsRegister(void)
{

  // Loads acting on LineStress element
  REGISTER_LOAD_EX(Element2DC0LinearLineStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);

  // Loads acting on Beam element
  REGISTER_LOAD_EX(Element2DC1Beam,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);

  // Loads acting on QuadrilateralStress element
  REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralStress,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on QuadrilateralMembrane element
  REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on TriangularStress element
  REGISTER_LOAD_EX(Element2DC0LinearTriangularStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element2DC0LinearTriangularStress,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on TriangularMembrane element
  REGISTER_LOAD_EX(Element2DC0LinearTriangularMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element2DC0LinearTriangularMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on HexahedronStrain element
  REGISTER_LOAD_EX(Element3DC0LinearHexahedronStrain,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element3DC0LinearHexahedronStrain,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on HexahedronMembrane element
  REGISTER_LOAD_EX(Element3DC0LinearHexahedronMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element3DC0LinearHexahedronMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Loads acting on Tetrahedron element
  REGISTER_LOAD_EX(Element3DC0LinearTetrahedronStrain,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element3DC0LinearTetrahedronStrain,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);
  REGISTER_LOAD_EX(Element3DC0LinearTetrahedronMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad);
  REGISTER_LOAD_EX(Element3DC0LinearTetrahedronMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad);

  // Add any additional loads here in a similar fashion...
  // Make sure that the pointer to the visit function is the correct one!!!

}

}} // end namespace itk::fem
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2006 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "BaseLocalPlayer.h"

/* common implementation headers */
#include "BZDBCache.h"

BaseLocalPlayer::BaseLocalPlayer(const PlayerId& _id,
				 const char* name, const char* _email,
				 const PlayerType _type) :
  Player(_id, RogueTeam, name, _email, _type),
  lastTime(TimeKeeper::getTick()),
  salt(0)
{
  lastPosition[0] = 0.0f;
  lastPosition[1] = 0.0f;
  lastPosition[2] = 0.0f;
  bbox[0][0] = bbox[1][0] = 0.0f;
  bbox[0][1] = bbox[1][1] = 0.0f;
  bbox[0][2] = bbox[1][2] = 0.0f;
}

BaseLocalPlayer::~BaseLocalPlayer()
{
  // do nothing
}

int BaseLocalPlayer::getSalt()
{
  salt = (salt + 1) & 127;
  return salt << 8;
}

void BaseLocalPlayer::update( float inputDT )
{
  // save last position
  const float* oldPosition = getPosition();
  lastPosition[0] = oldPosition[0];
  lastPosition[1] = oldPosition[1];
  lastPosition[2] = oldPosition[2];

  // update by time step
  float dt = float(TimeKeeper::getTick() - lastTime);
  lastTime = TimeKeeper::getTick();

  if (inputDT > 0)
	  dt = inputDT;

  if (dt < 0.001f)
	  dt = 0.001f;

  float fullDT = dt;
  float dtLimit = 0.1f;
  float doneDT = fullDT;
  if ( fullDT > dtLimit )
  {
	  dt = dtLimit;
	  doneDT-= dtLimit;
  }

  while (doneDT > 0)
  {
	doUpdateMotion(dt);

	// compute motion's bounding box around center of tank
	const float* newVelocity = getVelocity();
	bbox[0][0] = bbox[1][0] = oldPosition[0];
	bbox[0][1] = bbox[1][1] = oldPosition[1];
	bbox[0][2] = bbox[1][2] = oldPosition[2];
	if (newVelocity[0] > 0.0f)
		bbox[1][0] += dt * newVelocity[0];
	else
		bbox[0][0] += dt * newVelocity[0];
	if (newVelocity[1] > 0.0f)
		bbox[1][1] += dt * newVelocity[1];
	else
		bbox[0][1] += dt * newVelocity[1];
	if (newVelocity[2] > 0.0f)
		bbox[1][2] += dt * newVelocity[2];
	else
		bbox[0][2] += dt * newVelocity[2];

	// expand bounding box to include entire tank
	float size = BZDBCache::tankRadius;
	if (getFlag() == Flags::Obesity) size *= BZDB.eval(StateDatabase::BZDB_OBESEFACTOR);
	else if (getFlag() == Flags::Tiny) size *= BZDB.eval(StateDatabase::BZDB_TINYFACTOR);
	else if (getFlag() == Flags::Thief) size *= BZDB.eval(StateDatabase::BZDB_THIEFTINYFACTOR);
	bbox[0][0] -= size;
	bbox[1][0] += size;
	bbox[0][1] -= size;
	bbox[1][1] += size;
	bbox[1][2] += BZDBCache::tankHeight;

	// do remaining update stuff
	doUpdate(dt);

	// subtract another chunk
	doneDT =- dtLimit;
	if ( doneDT < dtLimit)	// if we only have a nubby left, don't do a full dt.
		dt = doneDT;
  }
}

Ray BaseLocalPlayer::getLastMotion() const
{
  return Ray(lastPosition, getVelocity());
}

const float (*BaseLocalPlayer::getLastMotionBBox() const)[3]
{
  return bbox;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>=- ~= -=<commit_after>/* bzflag
 * Copyright (c) 1993 - 2006 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "BaseLocalPlayer.h"

/* common implementation headers */
#include "BZDBCache.h"

BaseLocalPlayer::BaseLocalPlayer(const PlayerId& _id,
				 const char* name, const char* _email,
				 const PlayerType _type) :
  Player(_id, RogueTeam, name, _email, _type),
  lastTime(TimeKeeper::getTick()),
  salt(0)
{
  lastPosition[0] = 0.0f;
  lastPosition[1] = 0.0f;
  lastPosition[2] = 0.0f;
  bbox[0][0] = bbox[1][0] = 0.0f;
  bbox[0][1] = bbox[1][1] = 0.0f;
  bbox[0][2] = bbox[1][2] = 0.0f;
}

BaseLocalPlayer::~BaseLocalPlayer()
{
  // do nothing
}

int BaseLocalPlayer::getSalt()
{
  salt = (salt + 1) & 127;
  return salt << 8;
}

void BaseLocalPlayer::update( float inputDT )
{
  // save last position
  const float* oldPosition = getPosition();
  lastPosition[0] = oldPosition[0];
  lastPosition[1] = oldPosition[1];
  lastPosition[2] = oldPosition[2];

  // update by time step
  float dt = float(TimeKeeper::getTick() - lastTime);
  lastTime = TimeKeeper::getTick();

  if (inputDT > 0)
	  dt = inputDT;

  if (dt < 0.001f)
	  dt = 0.001f;

  float fullDT = dt;
  float dtLimit = 0.1f;
  float doneDT = fullDT;
  if ( fullDT > dtLimit )
  {
	  dt = dtLimit;
	  doneDT -= dtLimit;
  }

  while (doneDT > 0)
  {
	doUpdateMotion(dt);

	// compute motion's bounding box around center of tank
	const float* newVelocity = getVelocity();
	bbox[0][0] = bbox[1][0] = oldPosition[0];
	bbox[0][1] = bbox[1][1] = oldPosition[1];
	bbox[0][2] = bbox[1][2] = oldPosition[2];
	if (newVelocity[0] > 0.0f)
		bbox[1][0] += dt * newVelocity[0];
	else
		bbox[0][0] += dt * newVelocity[0];
	if (newVelocity[1] > 0.0f)
		bbox[1][1] += dt * newVelocity[1];
	else
		bbox[0][1] += dt * newVelocity[1];
	if (newVelocity[2] > 0.0f)
		bbox[1][2] += dt * newVelocity[2];
	else
		bbox[0][2] += dt * newVelocity[2];

	// expand bounding box to include entire tank
	float size = BZDBCache::tankRadius;
	if (getFlag() == Flags::Obesity) size *= BZDB.eval(StateDatabase::BZDB_OBESEFACTOR);
	else if (getFlag() == Flags::Tiny) size *= BZDB.eval(StateDatabase::BZDB_TINYFACTOR);
	else if (getFlag() == Flags::Thief) size *= BZDB.eval(StateDatabase::BZDB_THIEFTINYFACTOR);
	bbox[0][0] -= size;
	bbox[1][0] += size;
	bbox[0][1] -= size;
	bbox[1][1] += size;
	bbox[1][2] += BZDBCache::tankHeight;

	// do remaining update stuff
	doUpdate(dt);

	// subtract another chunk
	doneDT -= dtLimit;
	if ( doneDT < dtLimit)	// if we only have a nubby left, don't do a full dt.
		dt = doneDT;
  }
}

Ray BaseLocalPlayer::getLastMotion() const
{
  return Ray(lastPosition, getVelocity());
}

const float (*BaseLocalPlayer::getLastMotionBBox() const)[3]
{
  return bbox;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>