<commit_before>#include "i_render.h"

void TextUiModel::Draw( const Widget& Wdg )const
{
	static Font& Fnt(Font::Get());

	const Widget::Prop& TextProp=Wdg.GetProp(Widget::PT_Text);
	if(TextProp.Type!=Widget::Prop::T_Str)return;
	std::string Buf(TextProp.Value.ToStr);
	if(Buf.empty())return;
	glm::vec2 TexDim=Fnt.GetDim(Buf);
	if(TexDim.x<=std::numeric_limits<float>::epsilon())return;
	glm::vec4 Dim=Wdg.GetDimensions();
	Dim.z/=TexDim.x;
	glNormal3f(0.0, 0.0, 1.0);
	const Widget::Prop& ColorProp=Wdg.GetProp(Widget::PT_Color);
	uint32_t Color=(uint32_t)((ColorProp.Type==Widget::Prop::T_Int)?ColorProp.Value.ToInt:0xffffff);
	glColor3ub((Color>>16)&0xff,(Color>>8)&0xff,Color&0xff);
	glBindTexture(GL_TEXTURE_2D,Fnt.GetTexId());
	glBegin(GL_QUADS);	// UiModel QUADokat rajzol, igy egy begin-end-be beleferhetnenk akar
	for(std::string::const_iterator i=Buf.begin(),e=Buf.end();i!=e;++i)
	{
		SpritePhase const& Phase=Fnt.GetChar(*i);
		const float CharWidth=Dim.z*(Phase.Right-Phase.Left);
		glTexCoord2d( Phase.Left,   Phase.Top); glVertex3f(Dim.x,Dim.y+Dim.w,0);
		glTexCoord2d(Phase.Right,   Phase.Top); glVertex3f(Dim.x+CharWidth,Dim.y+Dim.w,0);
		glTexCoord2d(Phase.Right,Phase.Bottom); glVertex3f(Dim.x+CharWidth,Dim.y,0);
		glTexCoord2d( Phase.Left,Phase.Bottom); glVertex3f(Dim.x,Dim.y,0);
		Dim.x+=CharWidth;
	}
	glEnd();

}

<commit_msg>Fix text ratio<commit_after>#include "i_render.h"

void TextUiModel::Draw( const Widget& Wdg )const
{
	static Font& Fnt(Font::Get());

	const Widget::Prop& TextProp=Wdg.GetProp(Widget::PT_Text);
	if(TextProp.Type!=Widget::Prop::T_Str)return;
	std::string Buf(TextProp.Value.ToStr);
	if(Buf.empty())return;
	glm::vec2 TexDim=Fnt.GetDim(Buf);
	if(TexDim.x<=std::numeric_limits<float>::epsilon())return;
	glm::vec4 Dim=Wdg.GetDimensions();
	Dim.z/=TexDim.x;
	glNormal3f(0.0, 0.0, 1.0);
	const Widget::Prop& ColorProp=Wdg.GetProp(Widget::PT_Color);
	uint32_t Color=(uint32_t)((ColorProp.Type==Widget::Prop::T_Int)?ColorProp.Value.ToInt:0xffffff);
	glColor3ub((Color>>16)&0xff,(Color>>8)&0xff,Color&0xff);
	glBindTexture(GL_TEXTURE_2D,Fnt.GetTexId());
	glBegin(GL_QUADS);	// UiModel QUADokat rajzol, igy egy begin-end-be beleferhetnenk akar
	for(std::string::const_iterator i=Buf.begin(),e=Buf.end();i!=e;++i)
	{
		SpritePhase const& Phase=Fnt.GetChar(*i);
		const float CharWidth=Dim.z*(Phase.Right-Phase.Left);
		const float CharHeight=Dim.z*(Phase.Bottom-Phase.Top);
		glTexCoord2d( Phase.Left,   Phase.Top); glVertex3f(Dim.x,Dim.y+CharHeight,0);
		glTexCoord2d(Phase.Right,   Phase.Top); glVertex3f(Dim.x+CharWidth,Dim.y+CharHeight,0);
		glTexCoord2d(Phase.Right,Phase.Bottom); glVertex3f(Dim.x+CharWidth,Dim.y,0);
		glTexCoord2d( Phase.Left,Phase.Bottom); glVertex3f(Dim.x,Dim.y,0);
		Dim.x+=CharWidth;
	}
	glEnd();

}

<|endoftext|>


<commit_before>#include <ctime>
#include <stdlib.h>

#include "Utilities/Time.h"
#include "Utilities/Parameters.h"
#include "LibImages/LibImages.h"
#include "LibSift/LibSift.h"

#include "gdal.h"
#include "cpl_conv.h"

extern "C" {
    #include "pickopt.h"
}

static void print_help(char *v[])
{
    fprintf(stderr, "usage:\n\t%s file.tif x y w h [-o file]"
    //                          0 1        2 3 4 5
    //        " [-b] [--verbose] [--thresh-dog t (0.0133)]"
            " [--verbose] [--thresh-dog t (0.0133)]"
            " [--scale-space-noct n (8)] [--scale-space-nspo n (3)]\n", *v);
}

int main(int c, char *v[]) {
    if (c < 2) {
        print_help(v);
        return 1;
    }

    // initialise time
    Time time;

    // optional arguments
    const char *output_file = pick_option(&c, &v, "o", "/dev/stdout");
    //bool binary = (bool) pick_option(&c, &v, "b", NULL);
    bool verbose = (bool) pick_option(&c, &v, "-verbose", NULL);
    //int max_nb_pts = atoi(pick_option(&c, &v, "-max-nb-pts", "INT_MAX"));
    float thresh_dog = (float) atof(pick_option(&c, &v, "-thresh-dog", "0.0133"));
    int ss_noct = atoi(pick_option(&c, &v, "-scale-space-noct", "8"));
    int ss_nspo = atoi(pick_option(&c, &v, "-scale-space-nspo", "3"));

    // define the rectangular region of interest (roi)
    int x, y, w, h;
    if (c == 6) {
        x = atoi(v[2]);
        y = atoi(v[3]);
        w = atoi(v[4]);
        h = atoi(v[5]);
    } else {
        print_help(v);
        return 1;
    }

    // open the input image
    GDALAllRegister();
    GDALDatasetH hDataset = GDALOpen(v[1], GA_ReadOnly);
    if (hDataset == NULL) {
        fprintf(stderr, "ERROR: can't open %s\n", v[1]);
        return 1;
    }

    // clip roi to stay inside the image boundaries
    if (x < 0) {
        w += x;
        x = 0;
    }
    if (y < 0) {
        h += y;
        y = 0;
    }
    int size_x = GDALGetRasterXSize(hDataset);
    int size_y = GDALGetRasterYSize(hDataset);
    if (x + w > size_x)
        w = size_x - x;
    if (y + h > size_y)
        h = size_y - y;
    if (w <= 0 || h <= 0) {
        fprintf(stderr, "WARNING: empty roi\n");
        return 0;
    }

    // read roi
    GDALRasterBandH hBand = GDALGetRasterBand(hDataset, 1);
    float *roi = (float *) CPLMalloc(sizeof(float)*w*h);
    GDALRasterIO(hBand, GF_Read, x, y, w, h, roi, w, h, GDT_Float32, 0, 0);
    GDALClose(hDataset);
    if (verbose) time.get_time("read roi", 35);
    Image im(roi, (const size_t) w, (const size_t) h, 1);
    if (verbose) time.get_time("copy roi into Marc's image object", 35);
    CPLFree(roi);

    // prepare params object
    Parameters params;
    params.setDefaultValues();
    params.set_thresh_dog(thresh_dog);
    params.set_noct(ss_noct);
    params.set_nspo(ss_nspo);

    // run sift
    Sift sift(params);
    if (verbose) time.get_time("initialization", 35);
    sift.computeKeyPoints(im);
    if (verbose) time.get_time("compute keypoints", 35);

    // add (x, y) offset to keypoints coordinates
    std::list<KeyPoint*>::iterator key = sift.m_keyPoints->begin();
    for (; key != sift.m_keyPoints->end(); key++) {
        (*key)->setX((*key)->getX() + y); // in Ives' conventions x is the row index
        (*key)->setY((*key)->getY() + x);
    }
    if (verbose) time.get_time("add offset", 35);

    // write output
    sift.writeKeyPoints(output_file);
    if (verbose) time.get_time("write output", 35);
    return 0;
}
<commit_msg>[sift] use the whole image if no ROI is specified<commit_after>#include <ctime>
#include <stdlib.h>

#include "Utilities/Time.h"
#include "Utilities/Parameters.h"
#include "LibImages/LibImages.h"
#include "LibSift/LibSift.h"

#include "gdal.h"
#include "cpl_conv.h"

extern "C" {
    #include "pickopt.h"
}

static void print_help(char *v[])
{
    fprintf(stderr, "usage:\n\t%s file.tif [x y w h] [-o file]"
    //                          0 1        2 3 4 5
    //        " [-b] [--verbose] [--thresh-dog t (0.0133)]"
            " [--verbose] [--thresh-dog t (0.0133)]"
            " [--scale-space-noct n (8)] [--scale-space-nspo n (3)]\n", *v);
}

int main(int c, char *v[]) {
    if (c < 2) {
        print_help(v);
        return 1;
    }

    // initialise time
    Time time;

    // optional arguments
    const char *output_file = pick_option(&c, &v, "o", "/dev/stdout");
    //bool binary = (bool) pick_option(&c, &v, "b", NULL);
    bool verbose = (bool) pick_option(&c, &v, "-verbose", NULL);
    //int max_nb_pts = atoi(pick_option(&c, &v, "-max-nb-pts", "INT_MAX"));
    float thresh_dog = (float) atof(pick_option(&c, &v, "-thresh-dog", "0.0133"));
    int ss_noct = atoi(pick_option(&c, &v, "-scale-space-noct", "8"));
    int ss_nspo = atoi(pick_option(&c, &v, "-scale-space-nspo", "3"));

    // open the input image
    GDALAllRegister();
    GDALDatasetH hDataset = GDALOpen(v[1], GA_ReadOnly);
    if (hDataset == NULL) {
        fprintf(stderr, "ERROR: can't open %s\n", v[1]);
        return 1;
    }
    int size_x = GDALGetRasterXSize(hDataset);
    int size_y = GDALGetRasterYSize(hDataset);

    // define the rectangular region of interest (roi)
    int x, y, w, h;
    if (c == 6) {
        x = atoi(v[2]);
        y = atoi(v[3]);
        w = atoi(v[4]);
        h = atoi(v[5]);
    } else {
        x = 0;
        y = 0;
        w = size_x;
        h = size_y;
    }

    // clip roi to stay inside the image boundaries
    if (x < 0) {
        w += x;
        x = 0;
    }
    if (y < 0) {
        h += y;
        y = 0;
    }
    if (x + w > size_x)
        w = size_x - x;
    if (y + h > size_y)
        h = size_y - y;
    if (w <= 0 || h <= 0) {
        fprintf(stderr, "WARNING: empty roi\n");
        return 0;
    }

    // read roi
    GDALRasterBandH hBand = GDALGetRasterBand(hDataset, 1);
    float *roi = (float *) CPLMalloc(sizeof(float)*w*h);
    GDALRasterIO(hBand, GF_Read, x, y, w, h, roi, w, h, GDT_Float32, 0, 0);
    GDALClose(hDataset);
    if (verbose) time.get_time("read roi", 35);
    Image im(roi, (const size_t) w, (const size_t) h, 1);
    if (verbose) time.get_time("copy roi into Marc's image object", 35);
    CPLFree(roi);

    // prepare params object
    Parameters params;
    params.setDefaultValues();
    params.set_thresh_dog(thresh_dog);
    params.set_noct(ss_noct);
    params.set_nspo(ss_nspo);

    // run sift
    Sift sift(params);
    if (verbose) time.get_time("initialization", 35);
    sift.computeKeyPoints(im);
    if (verbose) time.get_time("compute keypoints", 35);

    // add (x, y) offset to keypoints coordinates
    std::list<KeyPoint*>::iterator key = sift.m_keyPoints->begin();
    for (; key != sift.m_keyPoints->end(); key++) {
        (*key)->setX((*key)->getX() + y); // in Ives' conventions x is the row index
        (*key)->setY((*key)->getY() + x);
    }
    if (verbose) time.get_time("add offset", 35);

    // write output
    sift.writeKeyPoints(output_file);
    if (verbose) time.get_time("write output", 35);
    return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
 *
 * KMail Folder Selection Tree Widget
 *
 * Copyright (c) 1997-1998 Stefan Taferner <taferner@kde.org>
 * Copyright (c) 2004-2005 Carsten Burghardt <burghardt@kde.org>
 * Copyright (c) 2008 Szymon Tomasz Stefanek <pragma@kvirc.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *****************************************************************************/

#include "folderselectiontreewidget.h"
#include "mainfolderview.h"
#include "kmfolder.h"
#include "kmfoldermgr.h"
#include "util.h"

#include <kaction.h>
#include <kmenu.h>
#include <kiconloader.h>
#include <kconfiggroup.h>

using namespace KMail::Util;

namespace KMail {

class FolderSelectionTreeWidgetItem : public KPIM::FolderTreeWidgetItem
{
public:
  FolderSelectionTreeWidgetItem(
      KPIM::FolderTreeWidget * listView,
      const FolderViewItem * srcItem
    )
    : KPIM::FolderTreeWidgetItem(
          listView, srcItem->labelText(),
          srcItem->protocol(), srcItem->folderType()
        ), mFolder( 0 ) {};

  FolderSelectionTreeWidgetItem(
      KPIM::FolderTreeWidgetItem * listViewItem,
      const FolderViewItem * srcItem
    )
    : KPIM::FolderTreeWidgetItem(
          listViewItem, srcItem->labelText(),
          srcItem->protocol(), srcItem->folderType()
        ), mFolder( 0 ) {};

public:
  void setFolder( KMFolder * folder )
    { mFolder = folder; };

  KMFolder * folder() const
    { return mFolder; };

private:
  KMFolder * mFolder;

};

FolderSelectionTreeWidget::FolderSelectionTreeWidget( QWidget * parent, ::KMail::MainFolderView * folderTree )
  : KPIM::FolderTreeWidget( parent ), mFolderTree( folderTree )
{
  setSelectionMode( QTreeWidget::SingleSelection );

  mNameColumnIndex = addColumn( i18n( "Folder" ) );
  mPathColumnIndex = addColumn( i18n( "Path" ) );

  setContextMenuPolicy( Qt::CustomContextMenu );
  connect( this, SIGNAL( customContextMenuRequested( const QPoint & ) ),
           this, SLOT( slotContextMenuRequested( const QPoint & ) ) );
  connect( this, SIGNAL( itemSelectionChanged() ),
           this, SLOT( slotItemSelectionChanged() ) );

  mCreateFolderAction = new KAction( KIcon( "folder-new" ),
                                     i18n("&New Subfolder..."), this );
  connect( mCreateFolderAction, SIGNAL( triggered() ),
           this, SLOT( addChildFolder() ) );
}

void FolderSelectionTreeWidget::recursiveReload( FolderViewItem *fti, FolderSelectionTreeWidgetItem *parent )
{
  // search folders are never shown
  if ( fti->protocol() == KPIM::FolderTreeWidgetItem::Search )
    return;

  // imap folders?
  if ( fti->protocol() == KPIM::FolderTreeWidgetItem::Imap && !mLastShowImapFolders )
    return;

  // the outbox?
  if ( fti->folderType() == KPIM::FolderTreeWidgetItem::Outbox && !mLastShowOutbox )
    return;

  // top level
  FolderSelectionTreeWidgetItem *item = parent ? new FolderSelectionTreeWidgetItem( parent, fti )
                                               : new FolderSelectionTreeWidgetItem( this, fti );

  item->setText( mNameColumnIndex, fti->labelText() );
  // Build the path (ParentItemPath/CurrentItemName)
  QString path;
  if( parent )
    path = parent->text( mPathColumnIndex ) + '/';
  path += fti->labelText();

  item->setText( mPathColumnIndex, path );
  QPixmap pix = fti->normalIcon();
  item->setIcon( mNameColumnIndex, pix.isNull() ? SmallIcon( "folder" ) : QIcon( pix ) );

  // Make readonly items unselectable, if we're told so
  if ( mLastMustBeReadWrite && ( fti->folder() && fti->folder()->isReadOnly() ) ) {
    item->setFlags( item->flags() & ~Qt::ItemIsSelectable );
  } else {
    item->setFolder( fti->folder() );
  }

  int cc = fti->childCount();
  int i = 0;

  while ( i < cc )
  {
    FolderViewItem *child = dynamic_cast<FolderViewItem *>( ( ( QTreeWidgetItem * )fti)->child( i ) );
    if ( child )
      recursiveReload( child, item );
    i++;
  }
}

void FolderSelectionTreeWidget::reload( bool mustBeReadWrite, bool showOutbox,
                               bool showImapFolders, const QString& preSelection )
{
  mLastMustBeReadWrite = mustBeReadWrite;
  mLastShowOutbox = showOutbox;
  mLastShowImapFolders = showImapFolders;

  clear();

  QString selected = preSelection;
  if ( selected.isEmpty() && folder() )
    selected = folder()->idString();

  mFilter.clear();

  int cc = mFolderTree->topLevelItemCount();

  int i = 0;

  // Calling setUpdatesEnabled() here causes weird effects (including crashes)
  // in the folder requester (used by the filtering dialog).
  // So disable it for now, this makes the folderselection dialog appear much
  // slower though :(
  //setUpdatesEnabled( false );

  while ( i < cc )
  {
    FolderViewItem *child = dynamic_cast<FolderViewItem *>( mFolderTree->topLevelItem( i ) );
    if ( child )
      recursiveReload( child, 0 );
    i++;
  }

  // we do this here in one go after all items have been created, as that is
  // faster than expanding each item, which triggers a lot of updates
  expandAll();

  if ( !preSelection.isEmpty() )
    setFolder( preSelection );
}

KMFolder * FolderSelectionTreeWidget::folder() const
{
  QTreeWidgetItem * item = currentItem();
  if ( item ) {
    if ( item->flags() & Qt::ItemIsSelectable )
      return static_cast<FolderSelectionTreeWidgetItem *>( item )->folder();
  }
  return 0;
}

void FolderSelectionTreeWidget::setFolder( KMFolder *folder )
{
  for ( QTreeWidgetItemIterator it( this ) ; *it ; ++it )
  {
    const KMFolder *fld = static_cast<FolderSelectionTreeWidgetItem *>( *it )->folder();
    if ( fld == folder )
    {
      ( *it )->setSelected( true );
      scrollToItem( *it );
      setCurrentItem( *it );
      return;
    }
  }
}

void FolderSelectionTreeWidget::setFolder( const QString& idString )
{
  setFolder( kmkernel->findFolderById( idString ) );
}

void FolderSelectionTreeWidget::addChildFolder()
{
  reconnectSignalSlotPair( kmkernel->folderMgr(), SIGNAL( folderAdded(KMFolder*) ),
           this, SLOT( slotFolderAdded(KMFolder*) ) );
  reconnectSignalSlotPair( kmkernel->imapFolderMgr(), SIGNAL( folderAdded(KMFolder*) ),
           this, SLOT( slotFolderAdded(KMFolder*) ) );
  reconnectSignalSlotPair( kmkernel->dimapFolderMgr(), SIGNAL( folderAdded(KMFolder*) ),
           this, SLOT( slotFolderAdded(KMFolder*) ) );
  mFolderTree->addChildFolder( folder(), parentWidget() );
}

void FolderSelectionTreeWidget::slotContextMenuRequested( const QPoint &p )
{
  QTreeWidgetItem * lvi = itemAt( p );

  if ( !lvi )
    return;
  setCurrentItem( lvi );
  lvi->setSelected( true );

  KMenu *folderMenu = new KMenu;
  folderMenu->addTitle( static_cast<FolderSelectionTreeWidgetItem *>( lvi )->labelText() );
  folderMenu->addAction( mCreateFolderAction );

  kmkernel->setContextMenuShown( true );
  folderMenu->exec ( viewport()->mapToGlobal( p ), 0);
  kmkernel->setContextMenuShown( false );
  delete folderMenu;
  folderMenu = 0;
}

void FolderSelectionTreeWidget::slotFolderAdded( KMFolder *addedFolder )
{
  reload( mLastMustBeReadWrite, mLastShowOutbox, mLastShowImapFolders );
  setFolder( addedFolder );
  disconnect( kmkernel->folderMgr(), SIGNAL( folderAdded(KMFolder*) ),
             this, SLOT( slotFolderAdded(KMFolder*) ) );
  disconnect( kmkernel->imapFolderMgr(), SIGNAL( folderAdded(KMFolder*) ),
             this, SLOT( slotFolderAdded(KMFolder*) ) );
  disconnect( kmkernel->dimapFolderMgr(), SIGNAL( folderAdded(KMFolder*) ),
             this, SLOT( slotFolderAdded(KMFolder*) ) );
}

void FolderSelectionTreeWidget::slotItemSelectionChanged()
{
  bool allowOk = true;
  bool allowCreate = true;

  const QList<QTreeWidgetItem *> selItems = selectedItems();
  if ( selItems.isEmpty() )				// no selection
    allowOk = allowCreate = false;
  else
  {
    const KMFolder *fld = static_cast<FolderSelectionTreeWidgetItem *>( selectedItems().first() )->folder();
    if ( !fld )						// "Local Folders" root
      allowOk = !mLastMustBeReadWrite;
    else						// any other folder
    {
      allowCreate = !fld->noChildren() && !fld->isReadOnly();
      if ( mLastMustBeReadWrite )
          allowOk = !fld->noContent() && !fld->isReadOnly();
    }
  }

  mCreateFolderAction->setEnabled( allowCreate );
  emit actionsAllowed( allowOk, allowCreate );
}

void FolderSelectionTreeWidget::applyFilter( const QString& filter )
{
  // We would like to set items that do not match the filter to disabled,
  // but that also disables all the children of that item (qt bug 181410,
  // closed as WONTFIX).
  // So instead, we mark the items as not selectable. That unfortunalty does not
  // give us visual feedback, though.
  // In keyPressEvent(), we change the behavior of the up/down arrow to skip
  // non-selectable items.

  if ( filter.isEmpty() )
  {
    // Empty filter:
    // reset all items to enabled, visible, expanded and not selected
    QTreeWidgetItemIterator clean( this );
    while ( QTreeWidgetItem *item = *clean )
    {
      item->setHidden( false );
      item->setSelected( false );
      item->setFlags( item->flags() | Qt::ItemIsSelectable );
      ++clean;
    }

    setColumnText( mPathColumnIndex, i18n("Path") );
    return;
  }

  // Not empty filter.
  // Reset all items to disabled, hidden, closed and not selected
  QTreeWidgetItemIterator clean( this );
  while ( QTreeWidgetItem *item = *clean )
  {
    item->setHidden( true );
    item->setSelected( false );
    item->setFlags( item->flags() & ~Qt::ItemIsSelectable );
    ++clean;
  }

  // Now search...
  QList<QTreeWidgetItem *> lItems = findItems( mFilter, Qt::MatchContains | Qt::MatchRecursive, mPathColumnIndex );

  for( QList<QTreeWidgetItem *>::Iterator it = lItems.begin(); it != lItems.end(); ++it )
  {
    ( *it )->setFlags( ( *it )->flags() | Qt::ItemIsSelectable );
    ( *it )->setHidden( false );

    // Open all the parents up to this item
    QTreeWidgetItem * p = ( *it )->parent();
    while( p )
    {
      p->setHidden( false );
      p = p->parent();
    }
  }

  // Iterate through the list to find the first selectable item
  QTreeWidgetItemIterator first( this );
  while ( FolderSelectionTreeWidgetItem * item = static_cast< FolderSelectionTreeWidgetItem* >( *first ) )
  {
    if ( ( !item->isHidden() ) && ( !item->isDisabled() ) &&
          ( item->flags() & Qt::ItemIsSelectable ) )
    {
      item->setSelected( true );
      setCurrentItem( item );
      scrollToItem( item );
      break;
    }
    ++first;
  }

  // Display and save the current filter
  if ( filter.length() > 0 )
    setColumnText( mPathColumnIndex, i18n("Path") + "  ( " + filter + " )" );
  else
    setColumnText( mPathColumnIndex, i18n("Path") );
}

void FolderSelectionTreeWidget::keyPressEvent( QKeyEvent *e )
{
  // Handle keyboard filtering.
  // Each key with text is appended to our search filter (which gets displayed
  // in the header for the Path column). Backpace removes text from the filter
  // while the del button clears the filter completely.

  switch( e->key() )
  {
    case Qt::Key_Backspace:
      if ( mFilter.length() > 0 )
        mFilter.truncate( mFilter.length()-1 );
      applyFilter( mFilter );
      return;
    break;
    case Qt::Key_Delete:
      mFilter = "";
      applyFilter( mFilter);
      return;
    break;

    // Reimplement up/down arrow handling to skip non-selectable items
    case Qt::Key_Up:
    {
      QTreeWidgetItem *newCurrent = currentItem();
      do {
        newCurrent = itemAbove( newCurrent );
      } while ( newCurrent && !( newCurrent->flags() & Qt::ItemIsSelectable ) );
      if ( newCurrent )
        setCurrentItem( newCurrent );
      return;
    }
    break;
    case Qt::Key_Down:
    {
      QTreeWidgetItem *newCurrent = currentItem();
      do {
        newCurrent = itemBelow( newCurrent );
      } while ( newCurrent && !( newCurrent->flags() & Qt::ItemIsSelectable ) );
      if ( newCurrent )
        setCurrentItem( newCurrent );
      return;
    }
    break;

    default:
    {
      QString s = e->text();
      if ( !s.isEmpty() && s.at( 0 ).isPrint() ) {
         mFilter += s;
        applyFilter( mFilter );
        return;
      }
    }
    break;
  }

  KPIM::FolderTreeWidget::keyPressEvent( e );
}

} // namespace KMail

#include "folderselectiontreewidget.moc"
<commit_msg>Backport r928047 by tmcguire from trunk to the 4.2 branch:<commit_after>/******************************************************************************
 *
 * KMail Folder Selection Tree Widget
 *
 * Copyright (c) 1997-1998 Stefan Taferner <taferner@kde.org>
 * Copyright (c) 2004-2005 Carsten Burghardt <burghardt@kde.org>
 * Copyright (c) 2008 Szymon Tomasz Stefanek <pragma@kvirc.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *****************************************************************************/

#include "folderselectiontreewidget.h"
#include "mainfolderview.h"
#include "kmfolder.h"
#include "kmfoldermgr.h"
#include "util.h"

#include <kaction.h>
#include <kmenu.h>
#include <kiconloader.h>
#include <kconfiggroup.h>

using namespace KMail::Util;

namespace KMail {

class FolderSelectionTreeWidgetItem : public KPIM::FolderTreeWidgetItem
{
public:
  FolderSelectionTreeWidgetItem(
      KPIM::FolderTreeWidget * listView,
      const FolderViewItem * srcItem
    )
    : KPIM::FolderTreeWidgetItem(
          listView, srcItem->labelText(),
          srcItem->protocol(), srcItem->folderType()
        ), mFolder( 0 ) {};

  FolderSelectionTreeWidgetItem(
      KPIM::FolderTreeWidgetItem * listViewItem,
      const FolderViewItem * srcItem
    )
    : KPIM::FolderTreeWidgetItem(
          listViewItem, srcItem->labelText(),
          srcItem->protocol(), srcItem->folderType()
        ), mFolder( 0 ) {};

public:
  void setFolder( KMFolder * folder )
    { mFolder = folder; };

  KMFolder * folder() const
    { return mFolder; };

private:
  KMFolder * mFolder;

};

FolderSelectionTreeWidget::FolderSelectionTreeWidget( QWidget * parent, ::KMail::MainFolderView * folderTree )
  : KPIM::FolderTreeWidget( parent ), mFolderTree( folderTree )
{
  setSelectionMode( QTreeWidget::SingleSelection );

  mNameColumnIndex = addColumn( i18n( "Folder" ) );
  mPathColumnIndex = addColumn( i18n( "Path" ) );

  setContextMenuPolicy( Qt::CustomContextMenu );
  connect( this, SIGNAL( customContextMenuRequested( const QPoint & ) ),
           this, SLOT( slotContextMenuRequested( const QPoint & ) ) );
  connect( this, SIGNAL( itemSelectionChanged() ),
           this, SLOT( slotItemSelectionChanged() ) );

  mCreateFolderAction = new KAction( KIcon( "folder-new" ),
                                     i18n("&New Subfolder..."), this );
  connect( mCreateFolderAction, SIGNAL( triggered() ),
           this, SLOT( addChildFolder() ) );
}

void FolderSelectionTreeWidget::recursiveReload( FolderViewItem *fti, FolderSelectionTreeWidgetItem *parent )
{
  // search folders are never shown
  if ( fti->protocol() == KPIM::FolderTreeWidgetItem::Search )
    return;

  // imap folders?
  if ( fti->protocol() == KPIM::FolderTreeWidgetItem::Imap && !mLastShowImapFolders )
    return;

  // the outbox?
  if ( fti->folderType() == KPIM::FolderTreeWidgetItem::Outbox && !mLastShowOutbox )
    return;

  // top level
  FolderSelectionTreeWidgetItem *item = parent ? new FolderSelectionTreeWidgetItem( parent, fti )
                                               : new FolderSelectionTreeWidgetItem( this, fti );

  item->setText( mNameColumnIndex, fti->labelText() );
  item->setIcon( 0, fti->icon( 0 ) );
  // Build the path (ParentItemPath/CurrentItemName)
  QString path;
  if( parent )
    path = parent->text( mPathColumnIndex ) + '/';
  path += fti->labelText();

  item->setText( mPathColumnIndex, path );

  // Make readonly items unselectable, if we're told so
  if ( mLastMustBeReadWrite && ( fti->folder() && fti->folder()->isReadOnly() ) ) {
    item->setFlags( item->flags() & ~Qt::ItemIsSelectable );
  } else {
    item->setFolder( fti->folder() );
  }

  int cc = fti->childCount();
  int i = 0;

  while ( i < cc )
  {
    FolderViewItem *child = dynamic_cast<FolderViewItem *>( ( ( QTreeWidgetItem * )fti)->child( i ) );
    if ( child )
      recursiveReload( child, item );
    i++;
  }
}

void FolderSelectionTreeWidget::reload( bool mustBeReadWrite, bool showOutbox,
                               bool showImapFolders, const QString& preSelection )
{
  mLastMustBeReadWrite = mustBeReadWrite;
  mLastShowOutbox = showOutbox;
  mLastShowImapFolders = showImapFolders;

  clear();

  QString selected = preSelection;
  if ( selected.isEmpty() && folder() )
    selected = folder()->idString();

  mFilter.clear();

  int cc = mFolderTree->topLevelItemCount();

  int i = 0;

  // Calling setUpdatesEnabled() here causes weird effects (including crashes)
  // in the folder requester (used by the filtering dialog).
  // So disable it for now, this makes the folderselection dialog appear much
  // slower though :(
  //setUpdatesEnabled( false );

  while ( i < cc )
  {
    FolderViewItem *child = dynamic_cast<FolderViewItem *>( mFolderTree->topLevelItem( i ) );
    if ( child )
      recursiveReload( child, 0 );
    i++;
  }

  // we do this here in one go after all items have been created, as that is
  // faster than expanding each item, which triggers a lot of updates
  expandAll();

  if ( !preSelection.isEmpty() )
    setFolder( preSelection );
}

KMFolder * FolderSelectionTreeWidget::folder() const
{
  QTreeWidgetItem * item = currentItem();
  if ( item ) {
    if ( item->flags() & Qt::ItemIsSelectable )
      return static_cast<FolderSelectionTreeWidgetItem *>( item )->folder();
  }
  return 0;
}

void FolderSelectionTreeWidget::setFolder( KMFolder *folder )
{
  for ( QTreeWidgetItemIterator it( this ) ; *it ; ++it )
  {
    const KMFolder *fld = static_cast<FolderSelectionTreeWidgetItem *>( *it )->folder();
    if ( fld == folder )
    {
      ( *it )->setSelected( true );
      scrollToItem( *it );
      setCurrentItem( *it );
      return;
    }
  }
}

void FolderSelectionTreeWidget::setFolder( const QString& idString )
{
  setFolder( kmkernel->findFolderById( idString ) );
}

void FolderSelectionTreeWidget::addChildFolder()
{
  reconnectSignalSlotPair( kmkernel->folderMgr(), SIGNAL( folderAdded(KMFolder*) ),
           this, SLOT( slotFolderAdded(KMFolder*) ) );
  reconnectSignalSlotPair( kmkernel->imapFolderMgr(), SIGNAL( folderAdded(KMFolder*) ),
           this, SLOT( slotFolderAdded(KMFolder*) ) );
  reconnectSignalSlotPair( kmkernel->dimapFolderMgr(), SIGNAL( folderAdded(KMFolder*) ),
           this, SLOT( slotFolderAdded(KMFolder*) ) );
  mFolderTree->addChildFolder( folder(), parentWidget() );
}

void FolderSelectionTreeWidget::slotContextMenuRequested( const QPoint &p )
{
  QTreeWidgetItem * lvi = itemAt( p );

  if ( !lvi )
    return;
  setCurrentItem( lvi );
  lvi->setSelected( true );

  KMenu *folderMenu = new KMenu;
  folderMenu->addTitle( static_cast<FolderSelectionTreeWidgetItem *>( lvi )->labelText() );
  folderMenu->addAction( mCreateFolderAction );

  kmkernel->setContextMenuShown( true );
  folderMenu->exec ( viewport()->mapToGlobal( p ), 0);
  kmkernel->setContextMenuShown( false );
  delete folderMenu;
  folderMenu = 0;
}

void FolderSelectionTreeWidget::slotFolderAdded( KMFolder *addedFolder )
{
  reload( mLastMustBeReadWrite, mLastShowOutbox, mLastShowImapFolders );
  setFolder( addedFolder );
  disconnect( kmkernel->folderMgr(), SIGNAL( folderAdded(KMFolder*) ),
             this, SLOT( slotFolderAdded(KMFolder*) ) );
  disconnect( kmkernel->imapFolderMgr(), SIGNAL( folderAdded(KMFolder*) ),
             this, SLOT( slotFolderAdded(KMFolder*) ) );
  disconnect( kmkernel->dimapFolderMgr(), SIGNAL( folderAdded(KMFolder*) ),
             this, SLOT( slotFolderAdded(KMFolder*) ) );
}

void FolderSelectionTreeWidget::slotItemSelectionChanged()
{
  bool allowOk = true;
  bool allowCreate = true;

  const QList<QTreeWidgetItem *> selItems = selectedItems();
  if ( selItems.isEmpty() )				// no selection
    allowOk = allowCreate = false;
  else
  {
    const KMFolder *fld = static_cast<FolderSelectionTreeWidgetItem *>( selectedItems().first() )->folder();
    if ( !fld )						// "Local Folders" root
      allowOk = !mLastMustBeReadWrite;
    else						// any other folder
    {
      allowCreate = !fld->noChildren() && !fld->isReadOnly();
      if ( mLastMustBeReadWrite )
          allowOk = !fld->noContent() && !fld->isReadOnly();
    }
  }

  mCreateFolderAction->setEnabled( allowCreate );
  emit actionsAllowed( allowOk, allowCreate );
}

void FolderSelectionTreeWidget::applyFilter( const QString& filter )
{
  // We would like to set items that do not match the filter to disabled,
  // but that also disables all the children of that item (qt bug 181410,
  // closed as WONTFIX).
  // So instead, we mark the items as not selectable. That unfortunalty does not
  // give us visual feedback, though.
  // In keyPressEvent(), we change the behavior of the up/down arrow to skip
  // non-selectable items.

  if ( filter.isEmpty() )
  {
    // Empty filter:
    // reset all items to enabled, visible, expanded and not selected
    QTreeWidgetItemIterator clean( this );
    while ( QTreeWidgetItem *item = *clean )
    {
      item->setHidden( false );
      item->setSelected( false );
      item->setFlags( item->flags() | Qt::ItemIsSelectable );
      ++clean;
    }

    setColumnText( mPathColumnIndex, i18n("Path") );
    return;
  }

  // Not empty filter.
  // Reset all items to disabled, hidden, closed and not selected
  QTreeWidgetItemIterator clean( this );
  while ( QTreeWidgetItem *item = *clean )
  {
    item->setHidden( true );
    item->setSelected( false );
    item->setFlags( item->flags() & ~Qt::ItemIsSelectable );
    ++clean;
  }

  // Now search...
  QList<QTreeWidgetItem *> lItems = findItems( mFilter, Qt::MatchContains | Qt::MatchRecursive, mPathColumnIndex );

  for( QList<QTreeWidgetItem *>::Iterator it = lItems.begin(); it != lItems.end(); ++it )
  {
    ( *it )->setFlags( ( *it )->flags() | Qt::ItemIsSelectable );
    ( *it )->setHidden( false );

    // Open all the parents up to this item
    QTreeWidgetItem * p = ( *it )->parent();
    while( p )
    {
      p->setHidden( false );
      p = p->parent();
    }
  }

  // Iterate through the list to find the first selectable item
  QTreeWidgetItemIterator first( this );
  while ( FolderSelectionTreeWidgetItem * item = static_cast< FolderSelectionTreeWidgetItem* >( *first ) )
  {
    if ( ( !item->isHidden() ) && ( !item->isDisabled() ) &&
          ( item->flags() & Qt::ItemIsSelectable ) )
    {
      item->setSelected( true );
      setCurrentItem( item );
      scrollToItem( item );
      break;
    }
    ++first;
  }

  // Display and save the current filter
  if ( filter.length() > 0 )
    setColumnText( mPathColumnIndex, i18n("Path") + "  ( " + filter + " )" );
  else
    setColumnText( mPathColumnIndex, i18n("Path") );
}

void FolderSelectionTreeWidget::keyPressEvent( QKeyEvent *e )
{
  // Handle keyboard filtering.
  // Each key with text is appended to our search filter (which gets displayed
  // in the header for the Path column). Backpace removes text from the filter
  // while the del button clears the filter completely.

  switch( e->key() )
  {
    case Qt::Key_Backspace:
      if ( mFilter.length() > 0 )
        mFilter.truncate( mFilter.length()-1 );
      applyFilter( mFilter );
      return;
    break;
    case Qt::Key_Delete:
      mFilter = "";
      applyFilter( mFilter);
      return;
    break;

    // Reimplement up/down arrow handling to skip non-selectable items
    case Qt::Key_Up:
    {
      QTreeWidgetItem *newCurrent = currentItem();
      do {
        newCurrent = itemAbove( newCurrent );
      } while ( newCurrent && !( newCurrent->flags() & Qt::ItemIsSelectable ) );
      if ( newCurrent )
        setCurrentItem( newCurrent );
      return;
    }
    break;
    case Qt::Key_Down:
    {
      QTreeWidgetItem *newCurrent = currentItem();
      do {
        newCurrent = itemBelow( newCurrent );
      } while ( newCurrent && !( newCurrent->flags() & Qt::ItemIsSelectable ) );
      if ( newCurrent )
        setCurrentItem( newCurrent );
      return;
    }
    break;

    default:
    {
      QString s = e->text();
      if ( !s.isEmpty() && s.at( 0 ).isPrint() ) {
         mFilter += s;
        applyFilter( mFilter );
        return;
      }
    }
    break;
  }

  KPIM::FolderTreeWidget::keyPressEvent( e );
}

} // namespace KMail

#include "folderselectiontreewidget.moc"
<|endoftext|>


<commit_before>#include "BaseGame.h"
#include "BlockFactory.h"
#include "Character.h"
#include "MagnetiteCore.h"
#include "Renderer.h"
#include "Chunk.h"
#include "BaseBlock.h"
#include "Camera.h"
#include "World.h"
#include "Explosion.h"

REG_GAME_TYPE( "default", BaseGame )

BaseGame::BaseGame()
{
	mEngine = MagnetiteCore::Singleton; // Bad design they say? Humbug!
	mPlayer = NULL;
	clickMode = "remove";
}

BaseGame::~BaseGame()
{

}

std::string BaseGame::getName()
{
	return "Default";
}

void BaseGame::_startGameSingle()
{
	mIsSinglePlayer = true;
	_startGame();
}

void BaseGame::_startGame()
{
	Util::log("#== Sandbox Game v0.1 ==================");
	Util::log("# is multiplayer: " + Util::toString( !isSingleplayer() ) );
}

bool BaseGame::isSingleplayer()
{
	return mIsSinglePlayer;
}

void BaseGame::_playerJoined()
{
	if( isSingleplayer() ) {
		mPlayer = createCharacter();
		playerJoin( mPlayer );
		playerSpawn( mPlayer );
	}
}

Character* BaseGame::getLocalPlayer()
{
	return mPlayer;
}

Character* BaseGame::createCharacter()
{
	return mEngine->createCharacter();
}

void BaseGame::_inputEvents( const InputEvent& e )
{
	if( e.event == Inputs::FORWARD ) {
		if( e.down )
			_inputMovement( Vector3( 0.f, 0.f, -1.f ) );
		else
			_inputMovement( Vector3( 0.f, 0.f, 1.f ) );
	}
	if( e.event == Inputs::LEFT ) {
		if( e.down )
			_inputMovement( Vector3( -1.f, 0.f, 0.f ) );
		else
			_inputMovement( Vector3( 1.f, 0.f, 0.f ) );
	}
	if( e.event == Inputs::RIGHT ) {
		if( e.down )
			_inputMovement( Vector3( 1.f, 0.f, 0.f ) );
		else
			_inputMovement( Vector3( -1.f, 0.f, 0.f ) );
	}
	if( e.event == Inputs::BACK ) {
		if( e.down )
			_inputMovement( Vector3( 0.f, 0.f, 1.f ) );
		else
			_inputMovement( Vector3( 0.f, 0.f, -1.f ) );
	}
	if( e.event == Inputs::JUMP && e.down ) {
		if( getLocalPlayer() ) mPlayer->jump();
	}
	if( e.event == Inputs::SPRINT ) {
		if( getLocalPlayer() ) mPlayer->enableSprint( e.down );
	}
	if( e.event == Inputs::FLY && e.down ) {
		if( getLocalPlayer() ) mPlayer->enableFlying( !mPlayer->isFlying() );
	}
	if( e.event == Inputs::RESPAWN && e.down ) {
		if( getLocalPlayer() ) mPlayer->setPosition( Vector3( 0, 150.f, 0 ) );
	}
}

void BaseGame::_inputMovement( const Vector3& v )
{
	if( getLocalPlayer() )
		mPlayer->addMoveDelta( v );
}

void BaseGame::_mouseMoved( const float x, const float y )
{
	if( getLocalPlayer() ) {
		mPlayer->getCamera()->pitch( y );
		mPlayer->getCamera()->yaw( x );
	}
}

void BaseGame::_primary()
{
	if( getLocalPlayer() ) {
		playerPrimaryClick( mPlayer );
	}
}

void BaseGame::_secondary()
{
	if( getLocalPlayer() ) {
		playerAltClick( mPlayer );
	}
}

//========= Events

void BaseGame::playerJoin( Character* player )
{
	Util::log( "A player just joined!" );
}

void BaseGame::playerSpawn( Character* player )
{
	if( player == mPlayer )
		Util::log( "You just spawned!" );
	player->setPosition( Vector3( 0.f, 120.f, 0.f )  );
}

void BaseGame::playerKilled( Character* player )
{
	if( player == mPlayer )
		Util::log( "You just died! D:" );
}

void BaseGame::characterDamage( Character* player )
{
	if( player == mPlayer )
		Util::log( "You're taking damage" );
}

void BaseGame::playerPrimaryClick( Character* player )
{
	raycast_r ray = player->getEyeCast();
	ray = mEngine->getWorld()->raycastWorld(ray);
	ray.maxDistance = 10;
	if(ray.hit)
	{
		if( clickMode == "remove" )
		{
			if(ray.chunk && ray.block)
			{
				ray.chunk->removeBlockAt( ray.blockIndex );
			}
		}
		else
		{
			explosion_t info;
			info.center = ray.worldHit + ray.hitNormal * 1.5;
			Explosion expl(info);
			expl.explode();
		}
	}
}

void BaseGame::playerAltClick( Character* player )
{
	raycast_r ray = player->getEyeCast();
	ray = mEngine->getWorld()->raycastWorld(ray);
	if(ray.hit && ray.block)
	{
		Util::log( Util::toString( ray.worldHit + ray.hitNormal ) );
		Vector3 cIndex = mEngine->getWorld()->worldToChunks( ray.worldHit + ray.hitNormal );
		Vector3 bIndex = mEngine->getWorld()->worldToBlock( ray.worldHit + (ray.hitNormal/2) );
		Chunk* chunk = mEngine->getWorld()->getChunk( cIndex.x, cIndex.y, cIndex.z );
		if(chunk) {
			BaseBlock* block = FactoryManager::getManager().createBlock( mEngine->getRenderer()->blockType );
			if( block != NULL ) {
				chunk->setBlockAt( block, bIndex.x, bIndex.y, bIndex.z );
			}
		}
	}
}

void BaseGame::uiPaint(Renderer* r)
{
	r->drawText(clickMode, 10, 50);
}

void BaseGame::keyDown( size_t evt )
{
	if( evt == sf::Keyboard::M )
	{
		if( clickMode == "remove" )
			clickMode = "explode";
		else clickMode = "remove";
	}
}

void BaseGame::keyUp( size_t evt )
{
}<commit_msg>block placement fix<commit_after>#include "BaseGame.h"
#include "BlockFactory.h"
#include "Character.h"
#include "MagnetiteCore.h"
#include "Renderer.h"
#include "Chunk.h"
#include "BaseBlock.h"
#include "Camera.h"
#include "World.h"
#include "Explosion.h"

REG_GAME_TYPE( "default", BaseGame )

BaseGame::BaseGame()
{
	mEngine = MagnetiteCore::Singleton; // Bad design they say? Humbug!
	mPlayer = NULL;
	clickMode = "remove";
}

BaseGame::~BaseGame()
{

}

std::string BaseGame::getName()
{
	return "Default";
}

void BaseGame::_startGameSingle()
{
	mIsSinglePlayer = true;
	_startGame();
}

void BaseGame::_startGame()
{
	Util::log("#== Sandbox Game v0.1 ==================");
	Util::log("# is multiplayer: " + Util::toString( !isSingleplayer() ) );
}

bool BaseGame::isSingleplayer()
{
	return mIsSinglePlayer;
}

void BaseGame::_playerJoined()
{
	if( isSingleplayer() ) {
		mPlayer = createCharacter();
		playerJoin( mPlayer );
		playerSpawn( mPlayer );
	}
}

Character* BaseGame::getLocalPlayer()
{
	return mPlayer;
}

Character* BaseGame::createCharacter()
{
	return mEngine->createCharacter();
}

void BaseGame::_inputEvents( const InputEvent& e )
{
	if( e.event == Inputs::FORWARD ) {
		if( e.down )
			_inputMovement( Vector3( 0.f, 0.f, -1.f ) );
		else
			_inputMovement( Vector3( 0.f, 0.f, 1.f ) );
	}
	if( e.event == Inputs::LEFT ) {
		if( e.down )
			_inputMovement( Vector3( -1.f, 0.f, 0.f ) );
		else
			_inputMovement( Vector3( 1.f, 0.f, 0.f ) );
	}
	if( e.event == Inputs::RIGHT ) {
		if( e.down )
			_inputMovement( Vector3( 1.f, 0.f, 0.f ) );
		else
			_inputMovement( Vector3( -1.f, 0.f, 0.f ) );
	}
	if( e.event == Inputs::BACK ) {
		if( e.down )
			_inputMovement( Vector3( 0.f, 0.f, 1.f ) );
		else
			_inputMovement( Vector3( 0.f, 0.f, -1.f ) );
	}
	if( e.event == Inputs::JUMP && e.down ) {
		if( getLocalPlayer() ) mPlayer->jump();
	}
	if( e.event == Inputs::SPRINT ) {
		if( getLocalPlayer() ) mPlayer->enableSprint( e.down );
	}
	if( e.event == Inputs::FLY && e.down ) {
		if( getLocalPlayer() ) mPlayer->enableFlying( !mPlayer->isFlying() );
	}
	if( e.event == Inputs::RESPAWN && e.down ) {
		if( getLocalPlayer() ) mPlayer->setPosition( Vector3( 0, 150.f, 0 ) );
	}
}

void BaseGame::_inputMovement( const Vector3& v )
{
	if( getLocalPlayer() )
		mPlayer->addMoveDelta( v );
}

void BaseGame::_mouseMoved( const float x, const float y )
{
	if( getLocalPlayer() ) {
		mPlayer->getCamera()->pitch( y );
		mPlayer->getCamera()->yaw( x );
	}
}

void BaseGame::_primary()
{
	if( getLocalPlayer() ) {
		playerPrimaryClick( mPlayer );
	}
}

void BaseGame::_secondary()
{
	if( getLocalPlayer() ) {
		playerAltClick( mPlayer );
	}
}

//========= Events

void BaseGame::playerJoin( Character* player )
{
	Util::log( "A player just joined!" );
}

void BaseGame::playerSpawn( Character* player )
{
	if( player == mPlayer )
		Util::log( "You just spawned!" );
	player->setPosition( Vector3( 0.f, 120.f, 0.f )  );
}

void BaseGame::playerKilled( Character* player )
{
	if( player == mPlayer )
		Util::log( "You just died! D:" );
}

void BaseGame::characterDamage( Character* player )
{
	if( player == mPlayer )
		Util::log( "You're taking damage" );
}

void BaseGame::playerPrimaryClick( Character* player )
{
	raycast_r ray = player->getEyeCast();
	ray = mEngine->getWorld()->raycastWorld(ray);
	ray.maxDistance = 10;
	if(ray.hit)
	{
		if( clickMode == "remove" )
		{
			if(ray.chunk && ray.block)
			{
				ray.chunk->removeBlockAt( ray.blockIndex );
			}
		}
		else
		{
			explosion_t info;
			info.center = ray.worldHit + ray.hitNormal * 1.5;
			Explosion expl(info);
			expl.explode();
		}
	}
}

void BaseGame::playerAltClick( Character* player )
{
	raycast_r ray = player->getEyeCast();
	ray = mEngine->getWorld()->raycastWorld(ray);
	if(ray.hit && ray.block)
	{
		BaseBlock* block = FactoryManager::getManager().createBlock( mEngine->getRenderer()->blockType );
		if( block != NULL ) {
			mEngine->getWorld()->setBlockAt( block, ray.worldHit.x + ray.hitNormal.x/2, ray.worldHit.y + ray.hitNormal.y/2, ray.worldHit.z + ray.hitNormal.z/2 );
		}
	}
}

void BaseGame::uiPaint(Renderer* r)
{
	r->drawText(clickMode, 10, 50);
}

void BaseGame::keyDown( size_t evt )
{
	if( evt == sf::Keyboard::M )
	{
		if( clickMode == "remove" )
			clickMode = "explode";
		else clickMode = "remove";
	}
}

void BaseGame::keyUp( size_t evt )
{
}<|endoftext|>


<commit_before>// Copyright 2017 Zuse Institute Berlin
//
//    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.

#pragma once

#include <array>
#include <iostream>
#include <string>
#include <stdexcept>

#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include "converter.hpp"
#include "exceptions.hpp"
#include "json/json.h"

#include "connection.hpp"

namespace scalaris {

  /// represents a TCP connection to Scalaris to execute JSON-RPC requests
  class TCPConnection : public Connection {
    boost::asio::io_service ioservice;
    boost::asio::ip::tcp::socket socket;
    //std::string hostname;
    //std::string link;
    //bool closed=false;
  public:
    /**
     * creates a connection instance
     * @param _hostname the host name of the Scalaris instance
     * @param _link the URL for JSON-RPC
     * @param port the TCP port of the Scalaris instance
     */
    TCPConnection(std::string _hostname,
                  std::string _link  = "jsonrpc.yaws");

    ~TCPConnection();

    /// checks whether the TCP connection is alive
    bool isOpen() const;

    /// closes the TCP connection
    void close();

    /// returns the server port of the TCP connection
    virtual unsigned get_port();

  private:
    virtual Json::Value exec_call(const std::string& methodname, Json::Value params);
    Json::Value process_result(const Json::Value& value);
  };
}
<commit_msg>c++: don't include ssl headers in tcp-connection<commit_after>// Copyright 2017-2018 Zuse Institute Berlin
//
//    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.

#pragma once

#include <array>
#include <iostream>
#include <string>
#include <stdexcept>

#include <boost/asio.hpp>
#include "converter.hpp"
#include "exceptions.hpp"
#include "json/json.h"

#include "connection.hpp"

namespace scalaris {

  /// represents a TCP connection to Scalaris to execute JSON-RPC requests
  class TCPConnection : public Connection {
    boost::asio::io_service ioservice;
    boost::asio::ip::tcp::socket socket;
    //std::string hostname;
    //std::string link;
    //bool closed=false;
  public:
    /**
     * creates a connection instance
     * @param _hostname the host name of the Scalaris instance
     * @param _link the URL for JSON-RPC
     * @param port the TCP port of the Scalaris instance
     */
    TCPConnection(std::string _hostname,
                  std::string _link  = "jsonrpc.yaws");

    ~TCPConnection();

    /// checks whether the TCP connection is alive
    bool isOpen() const;

    /// closes the TCP connection
    void close();

    /// returns the server port of the TCP connection
    virtual unsigned get_port();

  private:
    virtual Json::Value exec_call(const std::string& methodname, Json::Value params);
    Json::Value process_result(const Json::Value& value);
  };
}
<|endoftext|>


<commit_before>#pragma once
#include <cstdint>
#include <cstddef>
#include <type_traits>
#include <cassert>
#include <stdexcept>

template<typename T>
using if_unsigned_integral = std::enable_if_t<std::is_unsigned_v<T> && std::is_integral_v<T>, T>;

template<typename T>
using if_signed_integral = std::enable_if_t<std::is_signed_v<T> && std::is_integral_v<T>, T>;

template<typename T>
using if_floating_point = std::enable_if_t<std::is_floating_point_v<T>, T>;

template<typename T>
using if_bit_readable = std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, T>;

namespace rb::common {

    //--------------------------------------------------------------------------
    template<typename T>
    struct bit_read_helper
    {
        static constexpr const size_t max_bits = 8 * sizeof(T);
        static constexpr const size_t min_bits = 0;
        static constexpr const bool is_signed = std::is_signed_v<T>;
    };

    //--------------------------------------------------------------------------
    template<typename T>
    struct floating_point_bit_read_helper
    {
        static constexpr const size_t max_bits = 8 * sizeof(T);
        static constexpr const size_t min_bits = 8 * sizeof(T);
        static constexpr const bool is_signed = std::is_signed_v<T>;
    };

    //--------------------------------------------------------------------------
    template<> struct bit_read_helper<float>: floating_point_bit_read_helper<float> {};
    template<> struct bit_read_helper<double>: floating_point_bit_read_helper<double> {};
    template<> struct bit_read_helper<long double>: floating_point_bit_read_helper<long double> {};

    //--------------------------------------------------------------------------
    class bitreader {
    public:
        bitreader() = default;

        //----------------------------------------------------------------------
        void set_data(const uint8_t* data, size_t length) {
            _data = data;
            _data_end = data + length;
            _state.ptr = data;
            _next(_state);
        }

        //----------------------------------------------------------------------
        template<typename T>
        if_unsigned_integral<T> read(size_t bits)
        {
            _validate_read_dynamic<T>(bits);
            T ret = T(0);
            _read(_state, bits, ret);
            return ret;
        }

        //----------------------------------------------------------------------
        template<typename T>
        if_signed_integral<T> read(size_t bits)
        {
            _validate_read_dynamic<T>(bits);
            T ret = T(0);
            _read(_state, bits, ret);
            return _sign_extend(ret, bits);
        }

        //----------------------------------------------------------------------
        template<typename T>
        if_unsigned_integral<T> peek(size_t bits)
        {
            _validate_read_dynamic<T>(bits);
            T ret = T(0);
            _peek(_state, bits, ret);
            return ret;
        }

        //----------------------------------------------------------------------
        template<typename T>
        if_signed_integral<T> peek(size_t bits)
        {
            _validate_read_dynamic<T>(bits);
            T ret = T(0);
            _peek(_state, bits, ret);
            return _sign_extend(ret, bits);
        }

        //----------------------------------------------------------------------
        size_t position() const
        {
            return _position(_state);
        }

        //----------------------------------------------------------------------
        size_t available() const
        {
            return _available(_state);
        }

        //----------------------------------------------------------------------
        void seek(size_t bitpos)
        {
            size_t diff = _data_end - _data;
            if (diff*8 < bitpos) {
                throw std::runtime_error("Can't seek beyond bitstream size");
            }

            _state.ptr = _data;
            _skip(_state, bitpos);
        }

        //----------------------------------------------------------------------
        void align(size_t bits)
        {
            _align(_state, bits);
        }

        //----------------------------------------------------------------------
        void skip(size_t bits)
        {
            _skip(_state, bits);
        }

    private:
        //----------------------------------------------------------------------
        struct internal_state {
            uint64_t buffer = 0;
            size_t shift = 0;
            const uint8_t* ptr = nullptr;
        };

        //----------------------------------------------------------------------
        template<typename T>
        T _sign_extend(T raw, size_t bits)
        {
            T m = 1U << (bits - 1);
            return (raw ^ m) - m;
        }

        //----------------------------------------------------------------------
        void _next(internal_state& state) const
        {
            size_t available = std::min<size_t>(
                    sizeof(state.buffer),
                    _data_end - state.ptr);

            size_t to_read = available;
            while (to_read) {
                state.buffer <<= 8;
                state.buffer |= *state.ptr;
                ++state.ptr;
                --to_read;
            }
            state.shift = 8 * available;
        }

        //----------------------------------------------------------------------
        void _skip(internal_state& state, size_t bits) const
        {
            if (_available(state) < bits) {
                throw std::runtime_error("Cannot skip beyond end of bitstream");
            }

            static constexpr const size_t buffer_bits = sizeof(state.buffer) * 8;
            size_t leaps = bits / buffer_bits;
            if (leaps > 0) {
                state.ptr += leaps * buffer_bits;
                _next(state);
            }

            size_t rest = bits % buffer_bits;
            if (rest < state.shift) {
                state.shift -= rest;
            } else if (rest == state.shift) {
                _next(state);
            } else {
                rest -= state.shift;
                _next(state);
                state.shift -= rest;
            }
        }

        //----------------------------------------------------------------------
        size_t _position(const internal_state& state) const
        {
            return (_state.ptr - _data) * 8 - state.shift;
        }

        //----------------------------------------------------------------------
        size_t _available(const internal_state& state) const
        {
            return (_data_end - state.ptr) * 8 + state.shift;
        }

        //----------------------------------------------------------------------
        void _align(internal_state& state, size_t bits) const
        {
            size_t advance = _position(state) % bits;
            if (advance) {
                _skip(state, advance);
            }
        }

        //----------------------------------------------------------------------
        template<typename T>
        static constexpr T _mask(size_t bits)
        {
            return (bits == sizeof(T)*8) ? (~0) : ((T(1) << bits) - 1);
        }

        //----------------------------------------------------------------------
        template<typename T>
        void _elementary_read(internal_state& state, size_t bits, T& ret) const
        {
            state.shift -= bits;
            ret |= (state.buffer >> state.shift) & _mask<T>(bits);
        }

        //----------------------------------------------------------------------
        template<typename T>
        void _read(internal_state& state, size_t bits, T& ret) const
        {
            if (_available(state) < bits) {
                throw std::runtime_error("Cannot read beyond the bitstream data");
            }

            if (bits < state.shift) {
                _elementary_read(state, bits, ret);
            } else if (bits == state.shift) {
                _elementary_read(state, bits, ret);
                _next(state);
            } else {
                bits -= state.shift;
                _elementary_read(state, state.shift, ret);
                ret <<= bits;
                _next(state);
                _elementary_read(state, bits, ret);
            }
        }

        //----------------------------------------------------------------------
        template<typename T>
        void _peek(internal_state& state, size_t bits, T& ret) const
        {
            internal_state temporary = state;
            _read(temporary, bits, ret);
        }

        //----------------------------------------------------------------------
        template <typename T, size_t Size>
        constexpr void _validate_read_static() const
        {
            static_assert(Size <= bit_read_helper<T>::max_bits);
            static_assert(Size >= bit_read_helper<T>::min_bits);
        }

        //----------------------------------------------------------------------
        template <typename T>
        void _validate_read_dynamic(size_t size) const
        {
            assert(size <= bit_read_helper<T>::max_bits);
            assert(size >= bit_read_helper<T>::min_bits);
        }

        internal_state _state;
        const uint8_t* _data;
        const uint8_t* _data_end;
    };

}<commit_msg>Fix skip<commit_after>#pragma once
#include <cstdint>
#include <cstddef>
#include <type_traits>
#include <cassert>
#include <stdexcept>

template<typename T>
using if_unsigned_integral = std::enable_if_t<std::is_unsigned_v<T> && std::is_integral_v<T>, T>;

template<typename T>
using if_signed_integral = std::enable_if_t<std::is_signed_v<T> && std::is_integral_v<T>, T>;

template<typename T>
using if_floating_point = std::enable_if_t<std::is_floating_point_v<T>, T>;

template<typename T>
using if_bit_readable = std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, T>;

namespace rb::common {

    //--------------------------------------------------------------------------
    template<typename T>
    struct bit_read_helper
    {
        static constexpr const size_t max_bits = 8 * sizeof(T);
        static constexpr const size_t min_bits = 0;
        static constexpr const bool is_signed = std::is_signed_v<T>;
    };

    //--------------------------------------------------------------------------
    template<typename T>
    struct floating_point_bit_read_helper
    {
        static constexpr const size_t max_bits = 8 * sizeof(T);
        static constexpr const size_t min_bits = 8 * sizeof(T);
        static constexpr const bool is_signed = std::is_signed_v<T>;
    };

    //--------------------------------------------------------------------------
    template<> struct bit_read_helper<float>: floating_point_bit_read_helper<float> {};
    template<> struct bit_read_helper<double>: floating_point_bit_read_helper<double> {};
    template<> struct bit_read_helper<long double>: floating_point_bit_read_helper<long double> {};

    //--------------------------------------------------------------------------
    class bitreader {
    public:
        bitreader() = default;

        //----------------------------------------------------------------------
        void set_data(const uint8_t* data, size_t length) {
            _data = data;
            _data_end = data + length;
            _state.ptr = data;
            _next(_state);
        }

        //----------------------------------------------------------------------
        template<typename T>
        if_unsigned_integral<T> read(size_t bits)
        {
            _validate_read_dynamic<T>(bits);
            T ret = T(0);
            _read(_state, bits, ret);
            return ret;
        }

        //----------------------------------------------------------------------
        template<typename T>
        if_signed_integral<T> read(size_t bits)
        {
            _validate_read_dynamic<T>(bits);
            T ret = T(0);
            _read(_state, bits, ret);
            return _sign_extend(ret, bits);
        }

        //----------------------------------------------------------------------
        template<typename T>
        if_unsigned_integral<T> peek(size_t bits)
        {
            _validate_read_dynamic<T>(bits);
            T ret = T(0);
            _peek(_state, bits, ret);
            return ret;
        }

        //----------------------------------------------------------------------
        template<typename T>
        if_signed_integral<T> peek(size_t bits)
        {
            _validate_read_dynamic<T>(bits);
            T ret = T(0);
            _peek(_state, bits, ret);
            return _sign_extend(ret, bits);
        }

        //----------------------------------------------------------------------
        size_t position() const
        {
            return _position(_state);
        }

        //----------------------------------------------------------------------
        size_t available() const
        {
            return _available(_state);
        }

        //----------------------------------------------------------------------
        void seek(size_t bitpos)
        {
            size_t diff = _data_end - _data;
            if (diff*8 < bitpos) {
                throw std::runtime_error("Can't seek beyond bitstream size");
            }

            _state.ptr = _data;
            _skip(_state, bitpos);
        }

        //----------------------------------------------------------------------
        void align(size_t bits)
        {
            _align(_state, bits);
        }

        //----------------------------------------------------------------------
        void skip(size_t bits)
        {
            _skip(_state, bits);
        }

    private:
        //----------------------------------------------------------------------
        struct internal_state {
            uint64_t buffer = 0;
            size_t shift = 0;
            const uint8_t* ptr = nullptr;
        };

        //----------------------------------------------------------------------
        template<typename T>
        T _sign_extend(T raw, size_t bits)
        {
            T m = 1U << (bits - 1);
            return (raw ^ m) - m;
        }

        //----------------------------------------------------------------------
        void _next(internal_state& state) const
        {
            size_t available = std::min<size_t>(
                    sizeof(state.buffer),
                    _data_end - state.ptr);

            size_t to_read = available;
            while (to_read) {
                state.buffer <<= 8;
                state.buffer |= *state.ptr;
                ++state.ptr;
                --to_read;
            }
            state.shift = 8 * available;
        }

        //----------------------------------------------------------------------
        void _skip(internal_state& state, size_t bits) const
        {
            if (_available(state) < bits) {
                throw std::runtime_error("Cannot skip beyond end of bitstream");
            }

            if (bits < state.shift) {
                state.shift -= bits;
            } else if (bits == state.shift) {
                _next(state);
            } else {
                size_t to_skip = bits - state.shift;
                state.shift = 0;
                state.ptr += to_skip / 8;
                _next(state);
                state.shift -= to_skip % 8;
            }
        }

        //----------------------------------------------------------------------
        size_t _position(const internal_state& state) const
        {
            return (_state.ptr - _data) * 8 - state.shift;
        }

        //----------------------------------------------------------------------
        size_t _available(const internal_state& state) const
        {
            return (_data_end - state.ptr) * 8 + state.shift;
        }

        //----------------------------------------------------------------------
        void _align(internal_state& state, size_t bits) const
        {
            size_t advance = _position(state) % bits;
            if (advance) {
                _skip(state, advance);
            }
        }

        //----------------------------------------------------------------------
        template<typename T>
        static constexpr T _mask(size_t bits)
        {
            return (bits == sizeof(T)*8) ? (~0) : ((T(1) << bits) - 1);
        }

        //----------------------------------------------------------------------
        template<typename T>
        void _elementary_read(internal_state& state, size_t bits, T& ret) const
        {
            state.shift -= bits;
            ret |= (state.buffer >> state.shift) & _mask<T>(bits);
        }

        //----------------------------------------------------------------------
        template<typename T>
        void _read(internal_state& state, size_t bits, T& ret) const
        {
            if (_available(state) < bits) {
                throw std::runtime_error("Cannot read beyond the bitstream data");
            }

            if (bits < state.shift) {
                _elementary_read(state, bits, ret);
            } else if (bits == state.shift) {
                _elementary_read(state, bits, ret);
                _next(state);
            } else {
                bits -= state.shift;
                _elementary_read(state, state.shift, ret);
                ret <<= bits;
                _next(state);
                _elementary_read(state, bits, ret);
            }
        }

        //----------------------------------------------------------------------
        template<typename T>
        void _peek(internal_state& state, size_t bits, T& ret) const
        {
            internal_state temporary = state;
            _read(temporary, bits, ret);
        }

        //----------------------------------------------------------------------
        template <typename T, size_t Size>
        constexpr void _validate_read_static() const
        {
            static_assert(Size <= bit_read_helper<T>::max_bits);
            static_assert(Size >= bit_read_helper<T>::min_bits);
        }

        //----------------------------------------------------------------------
        template <typename T>
        void _validate_read_dynamic(size_t size) const
        {
            assert(size <= bit_read_helper<T>::max_bits);
            assert(size >= bit_read_helper<T>::min_bits);
        }

        internal_state _state;
        const uint8_t* _data;
        const uint8_t* _data_end;
    };

}<|endoftext|>


<commit_before>/* Copyright 2022 Stanford University
 *
 * 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.
 */

#include "stencil_mapper.h"

#include "mappers/default_mapper.h"

#define SPMD_SHARD_USE_IO_PROC 1

using namespace Legion;
using namespace Legion::Mapping;

static LegionRuntime::Logger::Category log_stencil("stencil");

class StencilMapper : public DefaultMapper
{
public:
  StencilMapper(MapperRuntime *rt, Machine machine, Processor local,
                const char *mapper_name,
                std::vector<Processor>* procs_list);
  virtual void select_task_options(const MapperContext    ctx,
                                   const Task&            task,
                                         TaskOptions&     output);
  virtual void default_policy_rank_processor_kinds(
                                    MapperContext ctx, const Task &task,
                                    std::vector<Processor::Kind> &ranking);
  virtual Processor default_policy_select_initial_processor(
                                    MapperContext ctx, const Task &task);
  virtual void default_policy_select_target_processors(
                                    MapperContext ctx,
                                    const Task &task,
                                    std::vector<Processor> &target_procs);
  virtual LogicalRegion default_policy_select_instance_region(
                                MapperContext ctx, Memory target_memory,
                                const RegionRequirement &req,
                                const LayoutConstraintSet &constraints,
                                bool force_new_instances,
                                bool meets_constraints);
  virtual void map_task(const MapperContext ctx,
                        const Task &task,
                        const MapTaskInput &input,
                        MapTaskOutput &output);
  virtual void map_copy(const MapperContext ctx,
                        const Copy &copy,
                        const MapCopyInput &input,
                        MapCopyOutput &output);
  template<bool IS_SRC>
  void stencil_create_copy_instance(MapperContext ctx, const Copy &copy,
                                    const RegionRequirement &req, unsigned index,
                                    std::vector<PhysicalInstance> &instances);
private:
  std::vector<Processor>& procs_list;
};

StencilMapper::StencilMapper(MapperRuntime *rt, Machine machine, Processor local,
                             const char *mapper_name,
                             std::vector<Processor>* _procs_list)
  : DefaultMapper(rt, machine, local, mapper_name)
  , procs_list(*_procs_list)
{
}

void StencilMapper::select_task_options(const MapperContext    ctx,
                                        const Task&            task,
                                              TaskOptions&     output)
{
  output.initial_proc = default_policy_select_initial_processor(ctx, task);
  output.inline_task = false;
  output.stealable = stealing_enabled;
#ifdef MAP_LOCALLY
  output.map_locally = true;
#else
  output.map_locally = false;
#endif
}

void StencilMapper::default_policy_rank_processor_kinds(MapperContext ctx,
                        const Task &task, std::vector<Processor::Kind> &ranking)
{
#if SPMD_SHARD_USE_IO_PROC
  const char* task_name = task.get_task_name();
  const char* prefix = "shard_";
  if (strncmp(task_name, prefix, strlen(prefix)) == 0) {
    // Put shard tasks on IO processors.
    ranking.resize(5);
    ranking[0] = Processor::TOC_PROC;
    ranking[1] = Processor::PROC_SET;
    ranking[2] = Processor::IO_PROC;
    ranking[3] = Processor::LOC_PROC;
    ranking[4] = Processor::PY_PROC;
  } else {
#endif
    ranking.resize(5);
    ranking[0] = Processor::TOC_PROC;
    ranking[1] = Processor::PROC_SET;
    ranking[2] = Processor::LOC_PROC;
    ranking[3] = Processor::IO_PROC;
    ranking[4] = Processor::PY_PROC;
#if SPMD_SHARD_USE_IO_PROC
  }
#endif
}

Processor StencilMapper::default_policy_select_initial_processor(
                                    MapperContext ctx, const Task &task)
{
  return DefaultMapper::default_policy_select_initial_processor(ctx, task);
}

void StencilMapper::default_policy_select_target_processors(
                                    MapperContext ctx,
                                    const Task &task,
                                    std::vector<Processor> &target_procs)
{
  target_procs.push_back(task.target_proc);
}

LogicalRegion StencilMapper::default_policy_select_instance_region(
                              MapperContext ctx, Memory target_memory,
                              const RegionRequirement &req,
                              const LayoutConstraintSet &constraints,
                              bool force_new_instances,
                              bool meets_constraints)
{
  return req.region;
}

void StencilMapper::map_task(const MapperContext      ctx,
                             const Task&              task,
                             const MapTaskInput&      input,
                                   MapTaskOutput&     output)
{
  if (task.parent_task != NULL && task.parent_task->must_epoch_task) {
    Processor::Kind target_kind = task.target_proc.kind();
    // Get the variant that we are going to use to map this task
    VariantInfo chosen = default_find_preferred_variant(task, ctx,
                                                        true/*needs tight bound*/, true/*cache*/, target_kind);
    output.chosen_variant = chosen.variant;
    // TODO: some criticality analysis to assign priorities
    output.task_priority = 0;
    output.postmap_task = false;
    // Figure out our target processors
    output.target_procs.push_back(task.target_proc);

    for (unsigned idx = 0; idx < task.regions.size(); idx++) {
      const RegionRequirement &req = task.regions[idx];

      // Skip any empty regions
      if ((req.privilege == NO_ACCESS) || (req.privilege_fields.empty()))
        continue;

      if (input.valid_instances[idx].empty()) {
        // happens when the region is empty
        output.chosen_instances[idx].resize(1);
        const LayoutConstraintSet empty_constraints;
        const std::vector<LogicalRegion> empty_regions(1, req.region);
        bool created = false;
        bool ok = runtime->find_or_create_physical_instance(ctx,
            default_policy_select_target_memory(ctx, task.target_proc, req),
            empty_constraints, empty_regions, output.chosen_instances[idx].back(),
            created, true/*acquire*/);
        if (!ok) {
          log_stencil.error("failed to find or create empty instance");
          assert(false);
        }
        continue;
      }
      assert(input.valid_instances[idx].size() == 1);
      output.chosen_instances[idx] = input.valid_instances[idx];
      bool ok = runtime->acquire_and_filter_instances(ctx, output.chosen_instances);
      if (!ok) {
        log_stencil.error("failed to acquire instances");
        assert(false);
      }
    }
    return;
  }

  DefaultMapper::map_task(ctx, task, input, output);
}

void StencilMapper::map_copy(const MapperContext ctx,
                             const Copy &copy,
                             const MapCopyInput &input,
                             MapCopyOutput &output)
{
  log_stencil.spew("Stencil mapper map_copy");
  for (unsigned idx = 0; idx < copy.src_requirements.size(); idx++)
  {
    // Always use a virtual instance for the source.
    output.src_instances[idx].clear();
    output.src_instances[idx].push_back(
      PhysicalInstance::get_virtual_instance());

    // Place the destination instance on the remote node.
    output.dst_instances[idx].clear();
    if (!copy.dst_requirements[idx].is_restricted()) {
      // Call a customized method to create an instance on the desired node.
      stencil_create_copy_instance<false/*is src*/>(ctx, copy,
        copy.dst_requirements[idx], idx, output.dst_instances[idx]);
    } else {
      // If it's restricted, just take the instance. This will only
      // happen inside the shard task.
      output.dst_instances[idx] = input.dst_instances[idx];
      if (!output.dst_instances[idx].empty())
        runtime->acquire_and_filter_instances(ctx,
                                output.dst_instances[idx]);
    }
  }
}

//--------------------------------------------------------------------------
template<bool IS_SRC>
void StencilMapper::stencil_create_copy_instance(MapperContext ctx,
                     const Copy &copy, const RegionRequirement &req,
                     unsigned idx, std::vector<PhysicalInstance> &instances)
//--------------------------------------------------------------------------
{
  // This method is identical to the default version except that it
  // chooses an intelligent memory based on the destination of the
  // copy.

  // See if we have all the fields covered
  std::set<FieldID> missing_fields = req.privilege_fields;
  for (std::vector<PhysicalInstance>::const_iterator it =
        instances.begin(); it != instances.end(); it++)
  {
    it->remove_space_fields(missing_fields);
    if (missing_fields.empty())
      break;
  }
  if (missing_fields.empty())
    return;
  // If we still have fields, we need to make an instance
  // We clearly need to take a guess, let's see if we can find
  // one of our instances to use.

  // ELLIOTT: Get the remote node here.
  Color index = runtime->get_logical_region_color(ctx, copy.src_requirements[idx].region);
  Memory target_memory = default_policy_select_target_memory(ctx,
                           procs_list[index % procs_list.size()],
                           req);
  log_stencil.warning("Building instance for copy of a region with index %u to be in memory %llx",
                      index, target_memory.id);
  bool force_new_instances = false;
  LayoutConstraintID our_layout_id =
   default_policy_select_layout_constraints(ctx, target_memory,
                                            req, COPY_MAPPING,
                                            true/*needs check*/,
                                            force_new_instances);
  LayoutConstraintSet creation_constraints =
              runtime->find_layout_constraints(ctx, our_layout_id);
  creation_constraints.add_constraint(
      FieldConstraint(missing_fields,
                      false/*contig*/, false/*inorder*/));
  instances.resize(instances.size() + 1);
  if (!default_make_instance(ctx, target_memory,
        creation_constraints, instances.back(),
        COPY_MAPPING, force_new_instances, true/*meets*/, req))
  {
    // If we failed to make it that is bad
    log_stencil.error("Stencil mapper failed allocation for "
                   "%s region requirement %d of explicit "
                   "region-to-region copy operation in task %s "
                   "(ID %lld) in memory " IDFMT " for processor "
                   IDFMT ". This means the working set of your "
                   "application is too big for the allotted "
                   "capacity of the given memory under the default "
                   "mapper's mapping scheme. You have three "
                   "choices: ask Realm to allocate more memory, "
                   "write a custom mapper to better manage working "
                   "sets, or find a bigger machine. Good luck!",
                   IS_SRC ? "source" : "destination", idx,
                   copy.parent_task->get_task_name(),
                   copy.parent_task->get_unique_id(),
		       target_memory.id,
		       copy.parent_task->current_proc.id);
    assert(false);
  }
}

static void create_mappers(Machine machine, Runtime *runtime, const std::set<Processor> &local_procs)
{
  std::vector<Processor>* procs_list = new std::vector<Processor>();

  Machine::ProcessorQuery procs_query(machine);
  procs_query.only_kind(Processor::LOC_PROC);
  for (Machine::ProcessorQuery::iterator it = procs_query.begin();
        it != procs_query.end(); it++)
    procs_list->push_back(*it);

  for (std::set<Processor>::const_iterator it = local_procs.begin();
        it != local_procs.end(); it++)
  {
    StencilMapper* mapper = new StencilMapper(runtime->get_mapper_runtime(),
                                              machine, *it, "stencil_mapper",
                                              procs_list);
    runtime->replace_default_mapper(mapper, *it);
  }
}

void register_mappers()
{
  Runtime::add_registration_callback(create_mappers);
}
<commit_msg>regent: Don't override select_task_options in Stencil.<commit_after>/* Copyright 2022 Stanford University
 *
 * 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.
 */

#include "stencil_mapper.h"

#include "mappers/default_mapper.h"

#define SPMD_SHARD_USE_IO_PROC 1

using namespace Legion;
using namespace Legion::Mapping;

static LegionRuntime::Logger::Category log_stencil("stencil");

class StencilMapper : public DefaultMapper
{
public:
  StencilMapper(MapperRuntime *rt, Machine machine, Processor local,
                const char *mapper_name,
                std::vector<Processor>* procs_list);
  virtual void default_policy_rank_processor_kinds(
                                    MapperContext ctx, const Task &task,
                                    std::vector<Processor::Kind> &ranking);
  virtual Processor default_policy_select_initial_processor(
                                    MapperContext ctx, const Task &task);
  virtual void default_policy_select_target_processors(
                                    MapperContext ctx,
                                    const Task &task,
                                    std::vector<Processor> &target_procs);
  virtual LogicalRegion default_policy_select_instance_region(
                                MapperContext ctx, Memory target_memory,
                                const RegionRequirement &req,
                                const LayoutConstraintSet &constraints,
                                bool force_new_instances,
                                bool meets_constraints);
  virtual void map_task(const MapperContext ctx,
                        const Task &task,
                        const MapTaskInput &input,
                        MapTaskOutput &output);
  virtual void map_copy(const MapperContext ctx,
                        const Copy &copy,
                        const MapCopyInput &input,
                        MapCopyOutput &output);
  template<bool IS_SRC>
  void stencil_create_copy_instance(MapperContext ctx, const Copy &copy,
                                    const RegionRequirement &req, unsigned index,
                                    std::vector<PhysicalInstance> &instances);
private:
  std::vector<Processor>& procs_list;
};

StencilMapper::StencilMapper(MapperRuntime *rt, Machine machine, Processor local,
                             const char *mapper_name,
                             std::vector<Processor>* _procs_list)
  : DefaultMapper(rt, machine, local, mapper_name)
  , procs_list(*_procs_list)
{
}

void StencilMapper::default_policy_rank_processor_kinds(MapperContext ctx,
                        const Task &task, std::vector<Processor::Kind> &ranking)
{
#if SPMD_SHARD_USE_IO_PROC
  const char* task_name = task.get_task_name();
  const char* prefix = "shard_";
  if (strncmp(task_name, prefix, strlen(prefix)) == 0) {
    // Put shard tasks on IO processors.
    ranking.resize(5);
    ranking[0] = Processor::TOC_PROC;
    ranking[1] = Processor::PROC_SET;
    ranking[2] = Processor::IO_PROC;
    ranking[3] = Processor::LOC_PROC;
    ranking[4] = Processor::PY_PROC;
  } else {
#endif
    ranking.resize(5);
    ranking[0] = Processor::TOC_PROC;
    ranking[1] = Processor::PROC_SET;
    ranking[2] = Processor::LOC_PROC;
    ranking[3] = Processor::IO_PROC;
    ranking[4] = Processor::PY_PROC;
#if SPMD_SHARD_USE_IO_PROC
  }
#endif
}

Processor StencilMapper::default_policy_select_initial_processor(
                                    MapperContext ctx, const Task &task)
{
  return DefaultMapper::default_policy_select_initial_processor(ctx, task);
}

void StencilMapper::default_policy_select_target_processors(
                                    MapperContext ctx,
                                    const Task &task,
                                    std::vector<Processor> &target_procs)
{
  target_procs.push_back(task.target_proc);
}

LogicalRegion StencilMapper::default_policy_select_instance_region(
                              MapperContext ctx, Memory target_memory,
                              const RegionRequirement &req,
                              const LayoutConstraintSet &constraints,
                              bool force_new_instances,
                              bool meets_constraints)
{
  return req.region;
}

void StencilMapper::map_task(const MapperContext      ctx,
                             const Task&              task,
                             const MapTaskInput&      input,
                                   MapTaskOutput&     output)
{
  if (task.parent_task != NULL && task.parent_task->must_epoch_task) {
    Processor::Kind target_kind = task.target_proc.kind();
    // Get the variant that we are going to use to map this task
    VariantInfo chosen = default_find_preferred_variant(task, ctx,
                                                        true/*needs tight bound*/, true/*cache*/, target_kind);
    output.chosen_variant = chosen.variant;
    // TODO: some criticality analysis to assign priorities
    output.task_priority = 0;
    output.postmap_task = false;
    // Figure out our target processors
    output.target_procs.push_back(task.target_proc);

    for (unsigned idx = 0; idx < task.regions.size(); idx++) {
      const RegionRequirement &req = task.regions[idx];

      // Skip any empty regions
      if ((req.privilege == NO_ACCESS) || (req.privilege_fields.empty()))
        continue;

      if (input.valid_instances[idx].empty()) {
        // happens when the region is empty
        output.chosen_instances[idx].resize(1);
        const LayoutConstraintSet empty_constraints;
        const std::vector<LogicalRegion> empty_regions(1, req.region);
        bool created = false;
        bool ok = runtime->find_or_create_physical_instance(ctx,
            default_policy_select_target_memory(ctx, task.target_proc, req),
            empty_constraints, empty_regions, output.chosen_instances[idx].back(),
            created, true/*acquire*/);
        if (!ok) {
          log_stencil.error("failed to find or create empty instance");
          assert(false);
        }
        continue;
      }
      assert(input.valid_instances[idx].size() == 1);
      output.chosen_instances[idx] = input.valid_instances[idx];
      bool ok = runtime->acquire_and_filter_instances(ctx, output.chosen_instances);
      if (!ok) {
        log_stencil.error("failed to acquire instances");
        assert(false);
      }
    }
    return;
  }

  DefaultMapper::map_task(ctx, task, input, output);
}

void StencilMapper::map_copy(const MapperContext ctx,
                             const Copy &copy,
                             const MapCopyInput &input,
                             MapCopyOutput &output)
{
  log_stencil.spew("Stencil mapper map_copy");
  for (unsigned idx = 0; idx < copy.src_requirements.size(); idx++)
  {
    // Always use a virtual instance for the source.
    output.src_instances[idx].clear();
    output.src_instances[idx].push_back(
      PhysicalInstance::get_virtual_instance());

    // Place the destination instance on the remote node.
    output.dst_instances[idx].clear();
    if (!copy.dst_requirements[idx].is_restricted()) {
      // Call a customized method to create an instance on the desired node.
      stencil_create_copy_instance<false/*is src*/>(ctx, copy,
        copy.dst_requirements[idx], idx, output.dst_instances[idx]);
    } else {
      // If it's restricted, just take the instance. This will only
      // happen inside the shard task.
      output.dst_instances[idx] = input.dst_instances[idx];
      if (!output.dst_instances[idx].empty())
        runtime->acquire_and_filter_instances(ctx,
                                output.dst_instances[idx]);
    }
  }
}

//--------------------------------------------------------------------------
template<bool IS_SRC>
void StencilMapper::stencil_create_copy_instance(MapperContext ctx,
                     const Copy &copy, const RegionRequirement &req,
                     unsigned idx, std::vector<PhysicalInstance> &instances)
//--------------------------------------------------------------------------
{
  // This method is identical to the default version except that it
  // chooses an intelligent memory based on the destination of the
  // copy.

  // See if we have all the fields covered
  std::set<FieldID> missing_fields = req.privilege_fields;
  for (std::vector<PhysicalInstance>::const_iterator it =
        instances.begin(); it != instances.end(); it++)
  {
    it->remove_space_fields(missing_fields);
    if (missing_fields.empty())
      break;
  }
  if (missing_fields.empty())
    return;
  // If we still have fields, we need to make an instance
  // We clearly need to take a guess, let's see if we can find
  // one of our instances to use.

  // ELLIOTT: Get the remote node here.
  Color index = runtime->get_logical_region_color(ctx, copy.src_requirements[idx].region);
  Memory target_memory = default_policy_select_target_memory(ctx,
                           procs_list[index % procs_list.size()],
                           req);
  log_stencil.warning("Building instance for copy of a region with index %u to be in memory %llx",
                      index, target_memory.id);
  bool force_new_instances = false;
  LayoutConstraintID our_layout_id =
   default_policy_select_layout_constraints(ctx, target_memory,
                                            req, COPY_MAPPING,
                                            true/*needs check*/,
                                            force_new_instances);
  LayoutConstraintSet creation_constraints =
              runtime->find_layout_constraints(ctx, our_layout_id);
  creation_constraints.add_constraint(
      FieldConstraint(missing_fields,
                      false/*contig*/, false/*inorder*/));
  instances.resize(instances.size() + 1);
  if (!default_make_instance(ctx, target_memory,
        creation_constraints, instances.back(),
        COPY_MAPPING, force_new_instances, true/*meets*/, req))
  {
    // If we failed to make it that is bad
    log_stencil.error("Stencil mapper failed allocation for "
                   "%s region requirement %d of explicit "
                   "region-to-region copy operation in task %s "
                   "(ID %lld) in memory " IDFMT " for processor "
                   IDFMT ". This means the working set of your "
                   "application is too big for the allotted "
                   "capacity of the given memory under the default "
                   "mapper's mapping scheme. You have three "
                   "choices: ask Realm to allocate more memory, "
                   "write a custom mapper to better manage working "
                   "sets, or find a bigger machine. Good luck!",
                   IS_SRC ? "source" : "destination", idx,
                   copy.parent_task->get_task_name(),
                   copy.parent_task->get_unique_id(),
		       target_memory.id,
		       copy.parent_task->current_proc.id);
    assert(false);
  }
}

static void create_mappers(Machine machine, Runtime *runtime, const std::set<Processor> &local_procs)
{
  std::vector<Processor>* procs_list = new std::vector<Processor>();

  Machine::ProcessorQuery procs_query(machine);
  procs_query.only_kind(Processor::LOC_PROC);
  for (Machine::ProcessorQuery::iterator it = procs_query.begin();
        it != procs_query.end(); it++)
    procs_list->push_back(*it);

  for (std::set<Processor>::const_iterator it = local_procs.begin();
        it != local_procs.end(); it++)
  {
    StencilMapper* mapper = new StencilMapper(runtime->get_mapper_runtime(),
                                              machine, *it, "stencil_mapper",
                                              procs_list);
    runtime->replace_default_mapper(mapper, *it);
  }
}

void register_mappers()
{
  Runtime::add_registration_callback(create_mappers);
}
<|endoftext|>