<commit_before>#include "Atm_controller.hpp"

const char Atm_controller::relOps[8] = "0=!<>-+";

Atm_controller& Atm_controller::begin( bool initialState /* = false */ ) {
  // clang-format off
  const static state_t state_table[] PROGMEM = {
    /*              ON_ENTER    ON_LOOP  ON_EXIT  EVT_ON  EVT_OFF  EVT_INPUT ELSE */
    /* OFF     */    ENT_OFF,        -1,      -1,     ON,      -1,       OFF,  -1,
    /* ON      */     ENT_ON,        -1,      -1,     -1,     OFF,        ON,  -1,
  };
  // clang-format on
  Machine::begin( state_table, ELSE );
  last_state = -1;
  state( initialState ? ON : OFF );
  indicator = -1;
  return *this;
}

int Atm_controller::event( int id ) {
  switch ( id ) {
    case EVT_ON:
      return eval_all();
    case EVT_OFF:
      return !eval_all();
  }
  return 0;
}

void Atm_controller::action( int id ) {
  switch ( id ) {
    case ENT_OFF:
      connector[last_state == current ? ON_INPUT_FALSE : ON_CHANGE_FALSE].push( state() );
      if ( indicator > -1 ) digitalWrite( indicator, !LOW != !indicatorActiveLow );
      last_state = current;
      return;
    case ENT_ON:
      if ( last_state != -1 ) connector[( last_state == current ) ? ON_INPUT_TRUE : ON_CHANGE_TRUE].push( state() );
      if ( indicator > -1 ) digitalWrite( indicator, !HIGH != !indicatorActiveLow );
      last_state = current;
      return;
  }
}

bool Atm_controller::eval_one( atm_connector& connector ) {
  switch ( connector.relOp() ) {
    case connector.REL_EQ:
      return connector.pull() == connector.event;
    case connector.REL_NEQ:
      return connector.pull() != connector.event;
    case connector.REL_LT:
      return connector.pull() < connector.event;
    case connector.REL_GT:
      return connector.pull() > connector.event;
    case connector.REL_LTE:
      return connector.pull() <= connector.event;
    case connector.REL_GTE:
      return connector.pull() >= connector.event;
  }
  return false;
}

bool Atm_controller::eval_all() {
  bool r = eval_one( operand[0] );
  for ( uint8_t i = 1; i < ATM_CONDITION_OPERAND_MAX; i++ ) {
    if ( operand[i].mode() ) {
      switch ( operand[i].logOp() ) {
        case atm_connector::LOG_AND:
          r = r && eval_one( operand[i] );
          break;
        case atm_connector::LOG_OR:
          r = r || eval_one( operand[i] );
          break;
        case atm_connector::LOG_XOR:
          r = !r != !eval_one( operand[i] );
          break;
      }
    }
  }
  return r;
}

Atm_controller& Atm_controller::led( int led, bool activeLow /* = false */ ) {
  indicator = led;
  indicatorActiveLow = activeLow;
  pinMode( indicator, OUTPUT );
  return *this;
}

Atm_controller& Atm_controller::onChange( bool status, atm_cb_push_t callback, int idx /* = 0 */ ) {
  connector[status ? ON_CHANGE_TRUE : ON_CHANGE_FALSE].set( callback, idx );
  return *this;
}

Atm_controller& Atm_controller::onChange( bool status, Machine& machine, int event /* = 0 */ ) {
  connector[status ? ON_CHANGE_TRUE : ON_CHANGE_FALSE].set( &machine, event );
  return *this;
}

Atm_controller& Atm_controller::onChange( atm_cb_push_t callback, int idx /* = 0 */ ) {
  connector[ON_CHANGE_TRUE].set( callback, idx );
  connector[ON_CHANGE_FALSE].set( callback, idx );
  return *this;
}

Atm_controller& Atm_controller::onChange( Machine& machine, int event /* = 0 */ ) {
  connector[ON_CHANGE_TRUE].set( &machine, event );
  connector[ON_CHANGE_FALSE].set( &machine, event );
  return *this;
}

Atm_controller& Atm_controller::onInput( bool status, atm_cb_push_t callback, int idx /* = 0 */ ) {
  connector[status ? ON_INPUT_TRUE : ON_INPUT_FALSE].set( callback, idx );
  return *this;
}

Atm_controller& Atm_controller::onInput( bool status, Machine& machine, int event /* = 0 */ ) {
  connector[status ? ON_INPUT_TRUE : ON_INPUT_FALSE].set( &machine, event );
  return *this;
}

Atm_controller& Atm_controller::IF( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_AND, machine, relOp, match );
}

Atm_controller& Atm_controller::IF( atm_cb_pull_t callback, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_AND, callback, relOp, match );
}

Atm_controller& Atm_controller::AND( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_AND, machine, relOp, match );
}

Atm_controller& Atm_controller::AND( atm_cb_pull_t callback, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_AND, callback, relOp, match );
}

Atm_controller& Atm_controller::OR( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_OR, machine, relOp, match );
}

Atm_controller& Atm_controller::OR( atm_cb_pull_t callback, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_OR, callback, relOp, match );
}

Atm_controller& Atm_controller::XOR( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_XOR, machine, relOp, match );
}

Atm_controller& Atm_controller::XOR( atm_cb_pull_t callback, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_XOR, callback, relOp, match );
}

Atm_controller& Atm_controller::OP( char logOp, Machine& machine, char relOp, int match ) {
  for ( uint8_t i = 0; i < ATM_CONDITION_OPERAND_MAX; i++ ) {
    if ( operand[i].mode() == atm_connector::MODE_NULL ) {  // Pick the first free slot
      operand[i].set( &machine, match, logOp, (int)( strchr( relOps, relOp ) - relOps ) );
      break;
    }
  }
  return *this;
}

Atm_controller& Atm_controller::OP( char logOp, atm_cb_pull_t callback, char relOp, int match ) {
  for ( uint8_t i = 0; i < ATM_CONDITION_OPERAND_MAX; i++ ) {
    if ( operand[i].mode() == atm_connector::MODE_NULL ) {  // Pick the first free slot
      operand[i].set( callback, match, logOp, (int)( strchr( relOps, relOp ) - relOps ) );
      break;
    }
  }
  return *this;
}

Atm_controller& Atm_controller::trace( Stream& stream ) {
  Machine::setTrace( &stream, atm_serial_debug::trace, "CONTROLLER\0EVT_ON\0EVT_OFF\0EVT_TOGGLE\0EVT_INPUT\0ELSE\0OFF\0ON" );
  return *this;
}
<commit_msg>Fixed trace symbols + pull bug warning<commit_after>#include "Atm_controller.hpp"

const char Atm_controller::relOps[8] = "0=!<>-+";

Atm_controller& Atm_controller::begin( bool initialState /* = false */ ) {
  // clang-format off
  const static state_t state_table[] PROGMEM = {
    /*              ON_ENTER    ON_LOOP  ON_EXIT  EVT_ON  EVT_OFF  EVT_INPUT ELSE */
    /* OFF     */    ENT_OFF,        -1,      -1,     ON,      -1,       OFF,  -1,
    /* ON      */     ENT_ON,        -1,      -1,     -1,     OFF,        ON,  -1,
  };
  // clang-format on
  Machine::begin( state_table, ELSE );
  last_state = -1;
  state( initialState ? ON : OFF );
  indicator = -1;
  return *this;
}

int Atm_controller::event( int id ) {
  switch ( id ) {
    case EVT_ON:
      return eval_all();
    case EVT_OFF:
      return !eval_all();
  }
  return 0;
}

void Atm_controller::action( int id ) {
  switch ( id ) {
    case ENT_OFF:
      connector[last_state == current ? ON_INPUT_FALSE : ON_CHANGE_FALSE].push( state() );
      if ( indicator > -1 ) digitalWrite( indicator, !LOW != !indicatorActiveLow );
      last_state = current;
      return;
    case ENT_ON:
      if ( last_state != -1 ) connector[( last_state == current ) ? ON_INPUT_TRUE : ON_CHANGE_TRUE].push( state() );
      if ( indicator > -1 ) digitalWrite( indicator, !HIGH != !indicatorActiveLow );
      last_state = current;
      return;
  }
}

bool Atm_controller::eval_one( atm_connector& connector ) {
  switch ( connector.relOp() ) {
    case connector.REL_EQ:
      return connector.pull() == connector.event;
    case connector.REL_NEQ:
      return connector.pull() != connector.event;
    case connector.REL_LT:
      return connector.pull() < connector.event;
    case connector.REL_GT:
      return connector.pull() > connector.event;
    case connector.REL_LTE:
      return connector.pull() <= connector.event;
    case connector.REL_GTE:
      return connector.pull() >= connector.event;
  }
  return false;
}

bool Atm_controller::eval_all() {
  bool r = eval_one( operand[0] );
  for ( uint8_t i = 1; i < ATM_CONDITION_OPERAND_MAX; i++ ) {
    if ( operand[i].mode() ) {
      switch ( operand[i].logOp() ) {
        case atm_connector::LOG_AND:
          r = r && eval_one( operand[i] );
          break;
        case atm_connector::LOG_OR:
          r = r || eval_one( operand[i] );
          break;
        case atm_connector::LOG_XOR:
          r = !r != !eval_one( operand[i] );
          break;
      }
    }
  }
  return r;
}

Atm_controller& Atm_controller::led( int led, bool activeLow /* = false */ ) {
  indicator = led;
  indicatorActiveLow = activeLow;
  pinMode( indicator, OUTPUT );
  return *this;
}

Atm_controller& Atm_controller::onChange( bool status, atm_cb_push_t callback, int idx /* = 0 */ ) {
  connector[status ? ON_CHANGE_TRUE : ON_CHANGE_FALSE].set( callback, idx );
  return *this;
}

Atm_controller& Atm_controller::onChange( bool status, Machine& machine, int event /* = 0 */ ) {
  connector[status ? ON_CHANGE_TRUE : ON_CHANGE_FALSE].set( &machine, event );
  return *this;
}

Atm_controller& Atm_controller::onChange( atm_cb_push_t callback, int idx /* = 0 */ ) {
  connector[ON_CHANGE_TRUE].set( callback, idx );
  connector[ON_CHANGE_FALSE].set( callback, idx );
  return *this;
}

Atm_controller& Atm_controller::onChange( Machine& machine, int event /* = 0 */ ) {
  connector[ON_CHANGE_TRUE].set( &machine, event );
  connector[ON_CHANGE_FALSE].set( &machine, event );
  return *this;
}

Atm_controller& Atm_controller::onInput( bool status, atm_cb_push_t callback, int idx /* = 0 */ ) {
  connector[status ? ON_INPUT_TRUE : ON_INPUT_FALSE].set( callback, idx );
  return *this;
}

Atm_controller& Atm_controller::onInput( bool status, Machine& machine, int event /* = 0 */ ) {
  connector[status ? ON_INPUT_TRUE : ON_INPUT_FALSE].set( &machine, event );
  return *this;
}

Atm_controller& Atm_controller::IF( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_AND, machine, relOp, match );
}

// BUG: pull operator does not pass the idx value!!!
Atm_controller& Atm_controller::IF( atm_cb_pull_t callback, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_AND, callback, relOp, match );
}

Atm_controller& Atm_controller::AND( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_AND, machine, relOp, match );
}

Atm_controller& Atm_controller::AND( atm_cb_pull_t callback, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_AND, callback, relOp, match );
}

Atm_controller& Atm_controller::OR( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_OR, machine, relOp, match );
}

Atm_controller& Atm_controller::OR( atm_cb_pull_t callback, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_OR, callback, relOp, match );
}

Atm_controller& Atm_controller::XOR( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_XOR, machine, relOp, match );
}

Atm_controller& Atm_controller::XOR( atm_cb_pull_t callback, char relOp /* = '>' */, int match /* = 0 */ ) {
  return OP( atm_connector::LOG_XOR, callback, relOp, match );
}

Atm_controller& Atm_controller::OP( char logOp, Machine& machine, char relOp, int match ) {
  for ( uint8_t i = 0; i < ATM_CONDITION_OPERAND_MAX; i++ ) {
    if ( operand[i].mode() == atm_connector::MODE_NULL ) {  // Pick the first free slot
      operand[i].set( &machine, match, logOp, (int)( strchr( relOps, relOp ) - relOps ) );
      break;
    }
  }
  return *this;
}

Atm_controller& Atm_controller::OP( char logOp, atm_cb_pull_t callback, char relOp, int match ) {
  for ( uint8_t i = 0; i < ATM_CONDITION_OPERAND_MAX; i++ ) {
    if ( operand[i].mode() == atm_connector::MODE_NULL ) {  // Pick the first free slot
      operand[i].set( callback, match, logOp, (int)( strchr( relOps, relOp ) - relOps ) );
      break;
    }
  }
  return *this;
}

Atm_controller& Atm_controller::trace( Stream& stream ) {
  Machine::setTrace( &stream, atm_serial_debug::trace, "CONTROLLER\0EVT_ON\0EVT_OFF\0EVT_INPUT\0ELSE\0OFF\0ON" );
  return *this;
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2855
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1758091 by chui@ocl-promo-incrementor on 2019/03/19 03:00:31<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2856
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2082
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1254065 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/04/03 03:00:10<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2083
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2008 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#include "PyExport.h"
#include "Exception.h"
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1))
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wdeprecated-register"
#elif defined (__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
namespace Swig_python {
#define SWIG_PYTHON_NO_BUILD_NONE
#include <swigpyrun.h>
#include "swigpyrun.inl"
}
#if defined(__clang__)
# pragma clang diagnostic pop
#elif defined (__GNUC__)
# pragma GCC diagnostic pop
#endif
#endif // HAVE_SWIG

<commit_msg>suppress -Wcast-function-type for swig code<commit_after>/***************************************************************************
 *   Copyright (c) 2008 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#include "PyExport.h"
#include "Exception.h"
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1))
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wdeprecated-register"
#elif defined (__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
# if __GNUC__ >= 8
# pragma GCC diagnostic ignored "-Wcast-function-type"
# endif
#endif
namespace Swig_python {
#define SWIG_PYTHON_NO_BUILD_NONE
#include <swigpyrun.h>
#include "swigpyrun.inl"
}
#if defined(__clang__)
# pragma clang diagnostic pop
#elif defined (__GNUC__)
# pragma GCC diagnostic pop
#endif
#endif // HAVE_SWIG

<|endoftext|>


<commit_before>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 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 Lesser General Public License for
more details.

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

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.

*/

#include "CityRegion.h"

#include "server/zone/Zone.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/object/ObjectManager.h"
#include "server/zone/objects/area/ActiveArea.h"
#include "server/zone/objects/scene/ObserverEventType.h"

void CityRegionImplementation::addActiveArea(Zone* zone, float x, float y, float radius) {
	ManagedReference<ActiveArea*> area = (ActiveArea*) ObjectManager::instance()->createObject(String("object/active_area.iff").hashCode(), 0, "");
	area->registerObserver(ObserverEventType::ENTEREDAREA, _this);
	area->registerObserver(ObserverEventType::EXITEDAREA, _this);
	area->initializePosition(x, 0, y);
	area->setRadius(radius);
	area->setClientObject(true);

	if (activeAreas.size() == 0) { //If this is the first active area, set it's planet map category to city.
		area->setPlanetMapCategory(TemplateManager::instance()->getPlanetMapCategoryByName("city"));
		area->getObjectName()->setStringId(regionName);
	}

	area->insertToZone(zone);

	activeAreas.put(area);
}

void CityRegionImplementation::notifyEnter(SceneObject* object) {
	object->setCityRegion(_this);

	//Check to see if the region already contains the objectid in its region objects
	if (regionObjects.contains(object->getObjectID()))
		return;

	Reference<PlanetMapCategory*> category = object->getPlanetMapCategory();
}

void CityRegionImplementation::notifyExit(SceneObject* object) {
	object->setCityRegion(NULL);
}

SortedVector<ManagedReference<SceneObject*> > CityRegionImplementation::getRegionObjectsByPlanetMapCategory(const String& catname) {
	SortedVector<ManagedReference<SceneObject*> > objects;

	for (int i = 0; i < regionObjects.size(); ++i) {
		ManagedReference<SceneObject*> object = regionObjects.get(i);

		if (object->getPlanetMapCategory() != NULL && object->getPlanetMapCategory()->getName() == catname)
			objects.put(object);
	}

	return objects;
}
<commit_msg>...<commit_after>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 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 Lesser General Public License for
more details.

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

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.

*/

#include "CityRegion.h"

#include "server/zone/Zone.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/object/ObjectManager.h"
#include "server/zone/objects/area/ActiveArea.h"
#include "server/zone/objects/scene/ObserverEventType.h"

void CityRegionImplementation::addActiveArea(Zone* zone, float x, float y, float radius) {
	ManagedReference<ActiveArea*> area = (ActiveArea*) ObjectManager::instance()->createObject(String("object/active_area.iff").hashCode(), 0, "");
	area->registerObserver(ObserverEventType::ENTEREDAREA, _this);
	area->registerObserver(ObserverEventType::EXITEDAREA, _this);
	area->initializePosition(x, 0, y);
	area->setRadius(radius);
	area->setClientObject(true);

	if (activeAreas.size() == 0) { //If this is the first active area, set it's planet map category to city.
		area->setPlanetMapCategory(TemplateManager::instance()->getPlanetMapCategoryByName("city"));
		area->getObjectName()->setStringId(regionName);
	}

	area->insertToZone(zone);

	activeAreas.put(area);
}

void CityRegionImplementation::notifyEnter(SceneObject* object) {
	object->setCityRegion(_this);
}

void CityRegionImplementation::notifyExit(SceneObject* object) {
	object->setCityRegion(NULL);
}

SortedVector<ManagedReference<SceneObject*> > CityRegionImplementation::getRegionObjectsByPlanetMapCategory(const String& catname) {
	SortedVector<ManagedReference<SceneObject*> > objects;

	for (int i = 0; i < regionObjects.size(); ++i) {
		ManagedReference<SceneObject*> object = regionObjects.get(i);

		if (object->getPlanetMapCategory() != NULL && object->getPlanetMapCategory()->getName() == catname)
			objects.put(object);
	}

	return objects;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

const int UFSIZE = 100010;
int union_find[UFSIZE];

void init() {
  for (auto i=0; i<UFSIZE; i++) {
    union_find[i] = i;
  }
}

int root(int a) {
  if (a == union_find[a]) return a;
  return (union_find[a] = root(union_find[a]));
}

bool issame(int a, int b) {
  return root(a) == root(b);
}

void unite(int a, int b) {
  union_find[root(a)] = root(b);
}

bool isroot(int a) {
  return root(a) == a;
}

int N, M;
int a[100010];
int b[100010];
int Q;
int x[100010];
int y[100010];
tuple<int, int> parent[100010];
int d[100010][20];
int depth[100010];
vector<int> V[100010];

int lca(int u, int v) {
  if (depth[u] > depth[v]) swap(u, v);
  for (auto k = 0; k < 20; ++k) {
    if ((depth[v] - depth[u]) >> k & 1) {
      v = d[v][k];
    }
  }
  if (u == v) return u;
  for (auto k = 19; k >= 0; --k) {
    if (d[k][u] != d[k][v]) {
      u = d[u][k];
      v = d[v][k];
    }
  }
  return d[u][0];
}

int main() {
  // initが必要
  init();
  fill(&d[0][0], &d[0][0]+100010*20, -1);
  fill(parent, parent+100010, make_tuple(-1, 0));
  cin >> N >> M;
  for (auto i = 0; i < M; ++i) {
    cin >> a[i] >> b[i];
    a[i]--;
    b[i]--;
  }
  cin >> Q;
  for (auto i = 0; i < Q; ++i) {
    cin >> x[i] >> y[i];
    x[i]--;
    y[i]--;
  }
  for (auto i = 0; i < M; ++i) {
    parent[root(a[i])] = make_tuple(root(b[i]), i);
    V[root(b[i])].push_back(root(a[i]));
    unite(a[i], b[i]);
  }
  for (auto i = 0; i < N; ++i) {
    d[i][0] = get<0>(parent[i]);
  }
  for (auto i = 1; i < 20; ++i) {
    for (auto j = 0; j < N; ++j) {
      if (d[j][i-1] >= 0) {
        d[j][i] = d[d[j][i-1]][i-1];
      }
    }
  }
  fill(depth, depth+100010, -1);
  for (auto i = 0; i < N; ++i) {
    if (d[i][0] == -1) {
      stack<tuple<int, int> > S;
      S.push(make_tuple(i, 0));
      while (!S.empty()) {
        int now = get<0>(S.top());
        int dep = get<1>(S.top());
        S.pop();
        if (depth[now] == -1) {
          depth[now] = dep;
          for (auto x : V[now]) {
            if (depth[x] == -1) {
              S.push(make_tuple(x, dep+1));
            }
          }
        }
      }
    }
  }
  for (auto i = 0; i < N; ++i) {
    cerr << "depth[" << i << "] = " << depth[i] << endl;
  }
  for (auto i = 0; i < Q; ++i) {
    if (!issame(x[i], y[i])) {
      cout << -1 << endl;
    } else {
      int c = lca(x[i], y[i]);
      cout << get<1>(parent[c])+1 << endl;
    }
  }
}
<commit_msg>tried H.cpp to 'H'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

const int UFSIZE = 100010;
int union_find[UFSIZE];

void init() {
  for (auto i=0; i<UFSIZE; i++) {
    union_find[i] = i;
  }
}

int root(int a) {
  if (a == union_find[a]) return a;
  return (union_find[a] = root(union_find[a]));
}

bool issame(int a, int b) {
  return root(a) == root(b);
}

void unite(int a, int b) {
  union_find[root(a)] = root(b);
}

bool isroot(int a) {
  return root(a) == a;
}

int N, M;
int a[100010];
int b[100010];
int Q;
int x[100010];
int y[100010];
tuple<int, int> parent[100010];
int d[100010][20];
int depth[100010];
vector<int> V[100010];

int lca(int u, int v) {
  if (depth[u] > depth[v]) swap(u, v);
  for (auto k = 0; k < 20; ++k) {
    if ((depth[v] - depth[u]) >> k & 1) {
      v = d[v][k];
    }
  }
  if (u == v) return u;
  for (auto k = 19; k >= 0; --k) {
    if (d[k][u] != d[k][v]) {
      u = d[u][k];
      v = d[v][k];
    }
  }
  return d[u][0];
}

int main() {
  // initが必要
  init();
  fill(&d[0][0], &d[0][0]+100010*20, -1);
  fill(parent, parent+100010, make_tuple(-1, 0));
  cin >> N >> M;
  for (auto i = 0; i < M; ++i) {
    cin >> a[i] >> b[i];
    a[i]--;
    b[i]--;
  }
  cin >> Q;
  for (auto i = 0; i < Q; ++i) {
    cin >> x[i] >> y[i];
    x[i]--;
    y[i]--;
  }
  for (auto i = 0; i < M; ++i) {
    parent[root(a[i])] = make_tuple(root(b[i]), i);
    cerr << "parent[" << root(a[i]) << "] = "
         << root(b[i]) << endl;
    V[root(b[i])].push_back(root(a[i]));
    unite(a[i], b[i]);
  }
  for (auto i = 0; i < N; ++i) {
    d[i][0] = get<0>(parent[i]);
  }
  for (auto i = 1; i < 20; ++i) {
    for (auto j = 0; j < N; ++j) {
      if (d[j][i-1] >= 0) {
        d[j][i] = d[d[j][i-1]][i-1];
      }
    }
  }
  fill(depth, depth+100010, -1);
  for (auto i = 0; i < N; ++i) {
    if (d[i][0] == -1) {
      stack<tuple<int, int> > S;
      S.push(make_tuple(i, 0));
      while (!S.empty()) {
        int now = get<0>(S.top());
        int dep = get<1>(S.top());
        S.pop();
        if (depth[now] == -1) {
          depth[now] = dep;
          for (auto x : V[now]) {
            if (depth[x] == -1) {
              S.push(make_tuple(x, dep+1));
            }
          }
        }
      }
    }
  }
  for (auto i = 0; i < N; ++i) {
    cerr << "depth[" << i << "] = " << depth[i] << endl;
  }
  for (auto i = 0; i < Q; ++i) {
    if (!issame(x[i], y[i])) {
      cout << -1 << endl;
    } else {
      int c = lca(x[i], y[i]);
      cout << get<1>(parent[c])+1 << endl;
    }
  }
}
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "DisplacedProblem.h"
#include "Problem.h"
#include "SubProblem.h"

class UpdateDisplacedMeshThread
{
public:
  UpdateDisplacedMeshThread(DisplacedProblem & problem) :
      _problem(problem),
      _ref_mesh(_problem.refMesh()),
      _nl_soln(*_problem._nl_solution),
      _aux_soln(*_problem._aux_solution)
  {
  }

  void operator() (const SemiLocalNodeRange & range) const
  {
    ParallelUniqueId puid;

    std::vector<std::string> & displacement_variables = _problem._displacements;
    unsigned int num_displacements = displacement_variables.size();

    std::vector<unsigned int> var_nums;
    std::vector<unsigned int> var_nums_directions;

    std::vector<unsigned int> aux_var_nums;
    std::vector<unsigned int> aux_var_nums_directions;

    for(unsigned int i=0; i<num_displacements; i++)
    {
      std::string displacement_name = displacement_variables[i];

      if(_problem._displaced_nl.sys().has_variable(displacement_name))
      {
         var_nums.push_back(_problem._displaced_nl.sys().variable_number(displacement_name));
         var_nums_directions.push_back(i);
      }
      else if(_problem._displaced_aux.sys().has_variable(displacement_name))
      {
         aux_var_nums.push_back(_problem._displaced_aux.sys().variable_number(displacement_name));
         aux_var_nums_directions.push_back(i);
      }
      else
        mooseError("Undefined variable used for displacements!");
    }

    unsigned int num_var_nums = var_nums.size();
    unsigned int num_aux_var_nums = aux_var_nums.size();

    unsigned int nonlinear_system_number = _problem._displaced_nl.sys().number();
    unsigned int aux_system_number = _problem._displaced_aux.sys().number();

    SemiLocalNodeRange::const_iterator nd = range.begin();

    for (nd = range.begin() ; nd != range.end(); ++nd)
    {
      Node & displaced_node = *(*nd);

      Node & reference_node = _ref_mesh.node(displaced_node.id());

      for(unsigned int i=0; i<num_var_nums; i++)
      {
        unsigned int direction = var_nums_directions[i];
        displaced_node(direction) = reference_node(direction) + _nl_soln(reference_node.dof_number(nonlinear_system_number, var_nums[i], 0));
      }

      for(unsigned int i=0; i<num_aux_var_nums; i++)
      {
        unsigned int direction = aux_var_nums_directions[i];
        displaced_node(direction) = reference_node(direction) + _aux_soln(reference_node.dof_number(aux_system_number, aux_var_nums[i], 0));
      }
    }
  }

protected:
  DisplacedProblem & _problem;
  MooseMesh & _ref_mesh;
  const NumericVector<Number> & _nl_soln;
  const NumericVector<Number> & _aux_soln;
};

DisplacedProblem::DisplacedProblem(MProblem & mproblem, MooseMesh & displaced_mesh, const std::vector<std::string> & displacements) :
    SubProblemInterface(),
    _problem(*mproblem.parent()),
    _mproblem(mproblem),
    _mesh(displaced_mesh),
    _eq(displaced_mesh),
    _ref_mesh(_mproblem.mesh()),
    _displacements(displacements),
    _displaced_nl(*this, _mproblem.getNonlinearSystem(), "DisplacedSystem"),
    _displaced_aux(*this, _mproblem.getAuxiliarySystem(), "DisplacedAuxSystem"),
    _geometric_search_data(_mproblem, _mesh),
    _ex(_eq)
{
  _mesh.prepare();

  _ex.sequence(true);

  unsigned int n_threads = libMesh::n_threads();
  _asm_info.resize(n_threads);
  for (unsigned int i = 0; i < n_threads; ++i)
    _asm_info[i] = new AssemblyData(_mesh);
}

DisplacedProblem::~DisplacedProblem()
{
  for (unsigned int i = 0; i < libMesh::n_threads(); ++i)
    delete _asm_info[i];
}

void
DisplacedProblem::init()
{
  _displaced_nl.init();
  _displaced_aux.init();

  Moose::setup_perf_log.push("DisplacedProblem::init::eq.init()","Setup");
  _eq.init();
  Moose::setup_perf_log.pop("DisplacedProblem::init::eq.init()","Setup");

  _eq.print_info(std::cout);

  Moose::setup_perf_log.push("DisplacedProblem::init::meshChanged()","Setup");
  _mesh.meshChanged();
  Moose::setup_perf_log.pop("DisplacedProblem::init::meshChanged()","Setup");

  Moose::setup_perf_log.push("DisplacedProblem::init::getQuadratureOrder()","Setup");
  Order qorder = _mproblem.getQuadratureOrder();
  Moose::setup_perf_log.pop("DisplacedProblem::init::getQuadratureOrder()","Setup");

  for (unsigned int tid = 0; tid < libMesh::n_threads(); ++tid)
    _asm_info[tid]->createQRules(qorder);
}

void
DisplacedProblem::updateMesh(const NumericVector<Number> & soln, const NumericVector<Number> & aux_soln)
{
  Moose::perf_log.push("updateDisplacedMesh()","Solve");

  (*_displaced_nl.sys().solution) = soln;
  (*_displaced_aux.sys().solution) = aux_soln;

  _nl_solution = &soln;
  _aux_solution = &aux_soln;

  Threads::parallel_for(*_mesh.getActiveSemiLocalNodeRange(), UpdateDisplacedMeshThread(*this));

  // Update the geometric searches that depend on the displaced mesh
  _geometric_search_data.update();

  Moose::perf_log.pop("updateDisplacedMesh()","Solve");
}

bool
DisplacedProblem::hasVariable(const std::string & var_name)
{
  if (_displaced_nl.hasVariable(var_name))
    return true;
  else if (_displaced_aux.hasVariable(var_name))
    return true;
  else
    return false;
}

MooseVariable &
DisplacedProblem::getVariable(THREAD_ID tid, const std::string & var_name)
{
  if (_displaced_nl.hasVariable(var_name))
    return _displaced_nl.getVariable(tid, var_name);
  else if (_displaced_aux.hasVariable(var_name))
    return _displaced_aux.getVariable(tid, var_name);
  else
    mooseError("No variable with name '" + var_name + "'");
}

void
DisplacedProblem::addVariable(const std::string & var_name, const FEType & type, Real scale_factor, const std::set< subdomain_id_type > * const active_subdomains)
{
  _displaced_nl.addVariable(var_name, type, scale_factor, active_subdomains);
}

void
DisplacedProblem::addAuxVariable(const std::string & var_name, const FEType & type, const std::set< subdomain_id_type > * const active_subdomains)
{
  _displaced_aux.addVariable(var_name, type, 1.0, active_subdomains);
}

void
DisplacedProblem::prepare(const Elem * elem, THREAD_ID tid)
{
  _asm_info[tid]->reinit(elem);
  _displaced_nl.prepare(tid);
  _displaced_aux.prepare(tid);
}

bool
DisplacedProblem::reinitDirac(const Elem * elem, THREAD_ID tid)
{
  std::set<Point> & points_set = _dirac_kernel_info._points[elem];

  bool have_points = points_set.size();

  if(have_points)
  {
    std::vector<Point> points(points_set.size());
    std::copy(points_set.begin(), points_set.end(), points.begin());

    _asm_info[tid]->reinitAtPhysical(elem, points);

    _displaced_nl.prepare(tid);
    _displaced_aux.prepare(tid);

    reinitElem(elem, tid);
  }

  return have_points;
}

void
DisplacedProblem::reinitElem(const Elem * elem, THREAD_ID tid)
{
  _displaced_nl.reinitElem(elem, tid);
  _displaced_aux.reinitElem(elem, tid);
}

void
DisplacedProblem::reinitElemFace(const Elem * elem, unsigned int side, unsigned int bnd_id, THREAD_ID tid)
{
  _asm_info[tid]->reinit(elem, side);
  _displaced_nl.reinitElemFace(elem, side, bnd_id, tid);
  _displaced_aux.reinitElemFace(elem, side, bnd_id, tid);
}

void
DisplacedProblem::reinitNode(const Node * node, THREAD_ID tid)
{
  _asm_info[tid]->reinit(node);
  _displaced_nl.reinitNode(node, tid);
  _displaced_aux.reinitNode(node, tid);
}

void
DisplacedProblem::reinitNodeFace(const Node * node, unsigned int bnd_id, THREAD_ID tid)
{
  _asm_info[tid]->reinit(node);
  _displaced_nl.reinitNodeFace(node, bnd_id, tid);
  _displaced_aux.reinitNodeFace(node, bnd_id, tid);
}

void
DisplacedProblem::getDiracElements(std::set<const Elem *> & elems)
{
  elems =_dirac_kernel_info._elements;
}

void
DisplacedProblem::clearDiracInfo()
{
  _dirac_kernel_info.clearPoints();
}

void
DisplacedProblem::updateGeomSearch()
{
  _geometric_search_data.update();
}

void
DisplacedProblem::output()
{
  // FIXME: use proper file_base
  _ex.output("out_displaced", _mproblem.time());
  _ex.meshChanged();
}

void
DisplacedProblem::meshChanged()
{
  // mesh changed
  _eq.reinit();
  _mesh.meshChanged();
  _geometric_search_data.update();
}

<commit_msg>remove second prepare<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "DisplacedProblem.h"
#include "Problem.h"
#include "SubProblem.h"

class UpdateDisplacedMeshThread
{
public:
  UpdateDisplacedMeshThread(DisplacedProblem & problem) :
      _problem(problem),
      _ref_mesh(_problem.refMesh()),
      _nl_soln(*_problem._nl_solution),
      _aux_soln(*_problem._aux_solution)
  {
  }

  void operator() (const SemiLocalNodeRange & range) const
  {
    ParallelUniqueId puid;

    std::vector<std::string> & displacement_variables = _problem._displacements;
    unsigned int num_displacements = displacement_variables.size();

    std::vector<unsigned int> var_nums;
    std::vector<unsigned int> var_nums_directions;

    std::vector<unsigned int> aux_var_nums;
    std::vector<unsigned int> aux_var_nums_directions;

    for(unsigned int i=0; i<num_displacements; i++)
    {
      std::string displacement_name = displacement_variables[i];

      if(_problem._displaced_nl.sys().has_variable(displacement_name))
      {
         var_nums.push_back(_problem._displaced_nl.sys().variable_number(displacement_name));
         var_nums_directions.push_back(i);
      }
      else if(_problem._displaced_aux.sys().has_variable(displacement_name))
      {
         aux_var_nums.push_back(_problem._displaced_aux.sys().variable_number(displacement_name));
         aux_var_nums_directions.push_back(i);
      }
      else
        mooseError("Undefined variable used for displacements!");
    }

    unsigned int num_var_nums = var_nums.size();
    unsigned int num_aux_var_nums = aux_var_nums.size();

    unsigned int nonlinear_system_number = _problem._displaced_nl.sys().number();
    unsigned int aux_system_number = _problem._displaced_aux.sys().number();

    SemiLocalNodeRange::const_iterator nd = range.begin();

    for (nd = range.begin() ; nd != range.end(); ++nd)
    {
      Node & displaced_node = *(*nd);

      Node & reference_node = _ref_mesh.node(displaced_node.id());

      for(unsigned int i=0; i<num_var_nums; i++)
      {
        unsigned int direction = var_nums_directions[i];
        displaced_node(direction) = reference_node(direction) + _nl_soln(reference_node.dof_number(nonlinear_system_number, var_nums[i], 0));
      }

      for(unsigned int i=0; i<num_aux_var_nums; i++)
      {
        unsigned int direction = aux_var_nums_directions[i];
        displaced_node(direction) = reference_node(direction) + _aux_soln(reference_node.dof_number(aux_system_number, aux_var_nums[i], 0));
      }
    }
  }

protected:
  DisplacedProblem & _problem;
  MooseMesh & _ref_mesh;
  const NumericVector<Number> & _nl_soln;
  const NumericVector<Number> & _aux_soln;
};

DisplacedProblem::DisplacedProblem(MProblem & mproblem, MooseMesh & displaced_mesh, const std::vector<std::string> & displacements) :
    SubProblemInterface(),
    _problem(*mproblem.parent()),
    _mproblem(mproblem),
    _mesh(displaced_mesh),
    _eq(displaced_mesh),
    _ref_mesh(_mproblem.mesh()),
    _displacements(displacements),
    _displaced_nl(*this, _mproblem.getNonlinearSystem(), "DisplacedSystem"),
    _displaced_aux(*this, _mproblem.getAuxiliarySystem(), "DisplacedAuxSystem"),
    _geometric_search_data(_mproblem, _mesh),
    _ex(_eq)
{
  _ex.sequence(true);

  unsigned int n_threads = libMesh::n_threads();
  _asm_info.resize(n_threads);
  for (unsigned int i = 0; i < n_threads; ++i)
    _asm_info[i] = new AssemblyData(_mesh);
}

DisplacedProblem::~DisplacedProblem()
{
  for (unsigned int i = 0; i < libMesh::n_threads(); ++i)
    delete _asm_info[i];
}

void
DisplacedProblem::init()
{
  _displaced_nl.init();
  _displaced_aux.init();

  Moose::setup_perf_log.push("DisplacedProblem::init::eq.init()","Setup");
  _eq.init();
  Moose::setup_perf_log.pop("DisplacedProblem::init::eq.init()","Setup");

  _eq.print_info(std::cout);

  Moose::setup_perf_log.push("DisplacedProblem::init::meshChanged()","Setup");
  _mesh.meshChanged();
  Moose::setup_perf_log.pop("DisplacedProblem::init::meshChanged()","Setup");

  Moose::setup_perf_log.push("DisplacedProblem::init::getQuadratureOrder()","Setup");
  Order qorder = _mproblem.getQuadratureOrder();
  Moose::setup_perf_log.pop("DisplacedProblem::init::getQuadratureOrder()","Setup");

  for (unsigned int tid = 0; tid < libMesh::n_threads(); ++tid)
    _asm_info[tid]->createQRules(qorder);
}

void
DisplacedProblem::updateMesh(const NumericVector<Number> & soln, const NumericVector<Number> & aux_soln)
{
  Moose::perf_log.push("updateDisplacedMesh()","Solve");

  (*_displaced_nl.sys().solution) = soln;
  (*_displaced_aux.sys().solution) = aux_soln;

  _nl_solution = &soln;
  _aux_solution = &aux_soln;

  Threads::parallel_for(*_mesh.getActiveSemiLocalNodeRange(), UpdateDisplacedMeshThread(*this));

  // Update the geometric searches that depend on the displaced mesh
  _geometric_search_data.update();

  Moose::perf_log.pop("updateDisplacedMesh()","Solve");
}

bool
DisplacedProblem::hasVariable(const std::string & var_name)
{
  if (_displaced_nl.hasVariable(var_name))
    return true;
  else if (_displaced_aux.hasVariable(var_name))
    return true;
  else
    return false;
}

MooseVariable &
DisplacedProblem::getVariable(THREAD_ID tid, const std::string & var_name)
{
  if (_displaced_nl.hasVariable(var_name))
    return _displaced_nl.getVariable(tid, var_name);
  else if (_displaced_aux.hasVariable(var_name))
    return _displaced_aux.getVariable(tid, var_name);
  else
    mooseError("No variable with name '" + var_name + "'");
}

void
DisplacedProblem::addVariable(const std::string & var_name, const FEType & type, Real scale_factor, const std::set< subdomain_id_type > * const active_subdomains)
{
  _displaced_nl.addVariable(var_name, type, scale_factor, active_subdomains);
}

void
DisplacedProblem::addAuxVariable(const std::string & var_name, const FEType & type, const std::set< subdomain_id_type > * const active_subdomains)
{
  _displaced_aux.addVariable(var_name, type, 1.0, active_subdomains);
}

void
DisplacedProblem::prepare(const Elem * elem, THREAD_ID tid)
{
  _asm_info[tid]->reinit(elem);
  _displaced_nl.prepare(tid);
  _displaced_aux.prepare(tid);
}

bool
DisplacedProblem::reinitDirac(const Elem * elem, THREAD_ID tid)
{
  std::set<Point> & points_set = _dirac_kernel_info._points[elem];

  bool have_points = points_set.size();

  if(have_points)
  {
    std::vector<Point> points(points_set.size());
    std::copy(points_set.begin(), points_set.end(), points.begin());

    _asm_info[tid]->reinitAtPhysical(elem, points);

    _displaced_nl.prepare(tid);
    _displaced_aux.prepare(tid);

    reinitElem(elem, tid);
  }

  return have_points;
}

void
DisplacedProblem::reinitElem(const Elem * elem, THREAD_ID tid)
{
  _displaced_nl.reinitElem(elem, tid);
  _displaced_aux.reinitElem(elem, tid);
}

void
DisplacedProblem::reinitElemFace(const Elem * elem, unsigned int side, unsigned int bnd_id, THREAD_ID tid)
{
  _asm_info[tid]->reinit(elem, side);
  _displaced_nl.reinitElemFace(elem, side, bnd_id, tid);
  _displaced_aux.reinitElemFace(elem, side, bnd_id, tid);
}

void
DisplacedProblem::reinitNode(const Node * node, THREAD_ID tid)
{
  _asm_info[tid]->reinit(node);
  _displaced_nl.reinitNode(node, tid);
  _displaced_aux.reinitNode(node, tid);
}

void
DisplacedProblem::reinitNodeFace(const Node * node, unsigned int bnd_id, THREAD_ID tid)
{
  _asm_info[tid]->reinit(node);
  _displaced_nl.reinitNodeFace(node, bnd_id, tid);
  _displaced_aux.reinitNodeFace(node, bnd_id, tid);
}

void
DisplacedProblem::getDiracElements(std::set<const Elem *> & elems)
{
  elems =_dirac_kernel_info._elements;
}

void
DisplacedProblem::clearDiracInfo()
{
  _dirac_kernel_info.clearPoints();
}

void
DisplacedProblem::updateGeomSearch()
{
  _geometric_search_data.update();
}

void
DisplacedProblem::output()
{
  // FIXME: use proper file_base
  _ex.output("out_displaced", _mproblem.time());
  _ex.meshChanged();
}

void
DisplacedProblem::meshChanged()
{
  // mesh changed
  _eq.reinit();
  _mesh.meshChanged();
  _geometric_search_data.update();
}

<|endoftext|>


<commit_before>#include "EncoderCounter.h"
#include "wiringPiInclude.h"

EncoderCounter::EncoderCounter(int channelA, int channelB, int ticksPerRev):
    m_channelA(channelA),
    m_channelB(channelB),
    m_count(0),
    m_lastTransition(-2),
    m_ticksPerRevolution(ticksPerRev)
{
    m_revolutionsPerTick = 1.0 / (double)ticksPerRev;
    pinMode(channelA, INPUT);
    pinMode(channelB, INPUT);
    m_channelAState = digitalRead(m_channelA);
    m_channelBState = digitalRead(m_channelB);
}

EncoderCounter::~EncoderCounter()
{

}

void* EncoderCounter::run()
{
    while (m_signal >= 0)
    {
        if (m_signal == 1) // Reset count
        {
            m_count = 0;
            m_signal = 0;
        }
        int newChannelAState = digitalRead(m_channelA);
        int newChannelBState = digitalRead(m_channelB);
        int newTransition = (newChannelAState != m_channelAState) ? 1 : (newChannelBState != m_channelBState) ? -1 : 0;
        // Calculate encoder speed in RPM, store in m_speed
        if (newTransition != 0)
        {
            std::chrono::high_resolution_clock::time_point newTime = std::chrono::high_resolution_clock::now();
            std::chrono::microseconds diffTime = std::chrono::duration_cast<std::chrono::microseconds>(newTime - m_lastTickTime);
            m_lastTickTime = newTime;
            m_speed = (m_revolutionsPerTick / (double)diffTime.count()) * 60000000.0;
        }
        m_channelAState = newChannelAState;
        m_channelBState = newChannelBState;
        // If last transition is uninitialized, initialize direction to whichever transition just occurred. It will
        // be forward if the A channel is read first, and backward if B is read first. Otherwise, direction
        // will be reversed if it reads two transitions from the same channel in sequence.
        m_direction = (m_lastTransition == -2) ? newTransition : (newTransition == m_lastTransition) ? -m_direction : m_direction;
        // Set last transition only if a new transition has occurred.
        m_lastTransition = (newTransition == 0) ? m_lastTransition : newTransition;
        // Add the direction (-1, 1) to the encoder count. If no transition has occurred, do nothing.
        m_count = (newTransition != 0) ? (long)m_count + m_direction : (long)m_count;
    }
    return NULL;
}

long EncoderCounter::getCount()
{
    return m_count;
}

void EncoderCounter::resetCount()
{
    this->signal(1);
}

std::list<Message*>* EncoderCounter::read()
{
    // TODO: finish stub, return a list with a speed and ticks message.
    std::list<Message*>* tmpList = new std::list<Message*>();
//    Message* tmpMessage = new Message();
    return tmpList;
}

double EncoderCounter::getSpeedRPM()
{
    return m_speed;
}
<commit_msg>Encoder now averages 10 readings.<commit_after>#include "EncoderCounter.h"
#include "wiringPiInclude.h"

EncoderCounter::EncoderCounter(int channelA, int channelB, int ticksPerRev):
    m_channelA(channelA),
    m_channelB(channelB),
    m_count(0),
    m_lastTransition(-2),
    m_ticksPerRevolution(ticksPerRev)
{
    m_revolutionsPerTick = 10.0 / (double)ticksPerRev;
    pinMode(channelA, INPUT);
    pinMode(channelB, INPUT);
    m_channelAState = digitalRead(m_channelA);
    m_channelBState = digitalRead(m_channelB);
}

EncoderCounter::~EncoderCounter()
{

}

void* EncoderCounter::run()
{
    int numTicks = 0;
    while (m_signal >= 0)
    {
        if (m_signal == 1) // Reset count
        {
            m_count = 0;
            m_signal = 0;
        }
        int newChannelAState = digitalRead(m_channelA);
        int newChannelBState = digitalRead(m_channelB);
        int newTransition = (newChannelAState != m_channelAState) ? 1 : (newChannelBState != m_channelBState) ? -1 : 0;
        // Calculate encoder speed in RPM, store in m_speed
        numTicks += abs(newTransition);
        if (numTicks >= 10)
        {
            numTicks = 0;
            std::chrono::high_resolution_clock::time_point newTime = std::chrono::high_resolution_clock::now();
            std::chrono::microseconds diffTime = std::chrono::duration_cast<std::chrono::microseconds>(newTime - m_lastTickTime);
            m_lastTickTime = newTime;
            m_speed = (m_revolutionsPerTick / (double)diffTime.count()) * 60000000.0;
        }
        m_channelAState = newChannelAState;
        m_channelBState = newChannelBState;
        // If last transition is uninitialized, initialize direction to whichever transition just occurred. It will
        // be forward if the A channel is read first, and backward if B is read first. Otherwise, direction
        // will be reversed if it reads two transitions from the same channel in sequence.
        m_direction = (m_lastTransition == -2) ? newTransition : (newTransition == m_lastTransition) ? -m_direction : m_direction;
        // Set last transition only if a new transition has occurred.
        m_lastTransition = (newTransition == 0) ? m_lastTransition : newTransition;
        // Add the direction (-1, 1) to the encoder count. If no transition has occurred, do nothing.
        m_count = (newTransition != 0) ? (long)m_count + m_direction : (long)m_count;
    }
    return NULL;
}

long EncoderCounter::getCount()
{
    return m_count;
}

void EncoderCounter::resetCount()
{
    this->signal(1);
}

std::list<Message*>* EncoderCounter::read()
{
    // TODO: finish stub, return a list with a speed and ticks message.
    std::list<Message*>* tmpList = new std::list<Message*>();
//    Message* tmpMessage = new Message();
    return tmpList;
}

double EncoderCounter::getSpeedRPM()
{
    return m_speed;
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platform/platform.h"

#include "ts/tsShapeInstance.h"
#include "ts/tsMaterialList.h"
#include "core/strings/stringFunctions.h"

//-------------------------------------------------------------------------------------
// Dump shape structure:
//-------------------------------------------------------------------------------------

#define dumpLine(buffer) {str = buffer; stream.write((int)dStrlen(str),str);}

void TSShapeInstance::dumpNode(Stream & stream ,S32 level, S32 nodeIndex, Vector<S32> & detailSizes)
{
   if (nodeIndex < 0)
      return;

   // limit level to prevent overflow
   if (level > 160)
      level = 160;

   S32 i;
   const char * str;
   char space[512];
   for (i = 0; i < level*3; i++)
      space[i] = ' ';
   space[level*3] = '\0';

   const char *nodeName = "";
   const TSShape::Node & node = mShape->nodes[nodeIndex];
   if (node.nameIndex != -1)
     nodeName = mShape->getName(node.nameIndex);
   dumpLine(avar("%s%s", space, nodeName));

   // find all the objects that hang off this node...
   Vector<ObjectInstance*> objectList;
   for (i=0; i<mMeshObjects.size(); i++)
      if (mMeshObjects[i].nodeIndex == nodeIndex)
         objectList.push_back(&mMeshObjects[i]);

   if (objectList.size() == 0)
      dumpLine("\r\n");

   S32 spaceCount = -1;
   for (S32 j=0;j<objectList.size(); j++)
   {
      // should be a dynamic cast, but MSVC++ has problems with this...
      MeshObjectInstance * obj = (MeshObjectInstance *)(objectList[j]);
      if (!obj)
         continue;

      // object name
      const char *objectName = "";
      if (obj->object->nameIndex!=-1)
         objectName = mShape->getName(obj->object->nameIndex);

      // more spaces if this is the second object on this node
      if (spaceCount>0)
      {
         char buf[2048];
         dMemset(buf,' ',spaceCount);
         buf[spaceCount] = '\0';
         dumpLine(buf);
      }

      // dump object name
      dumpLine(avar(" --> Object %s with following details: ",objectName));

      // dump object detail levels
      for (S32 k=0; k<obj->object->numMeshes; k++)
      {
         S32 f = obj->object->startMeshIndex;
         if (mShape->meshes[f+k])
            dumpLine(avar(" %i",detailSizes[k]));
      }

      dumpLine("\r\n");

      // how many spaces should we prepend if we have another object on this node
      if (spaceCount<0)
         spaceCount = (S32)(dStrlen(space) + dStrlen(nodeName));

      if(spaceCount > 2000)
         spaceCount = 2000;
   }

   // search for children
   for (S32 k=nodeIndex+1; k<mShape->nodes.size(); k++)
   {
      if (mShape->nodes[k].parentIndex == nodeIndex)
         // this is our child
         dumpNode(stream, level+1, k, detailSizes);
   }
}

void TSShapeInstance::dump(Stream & stream)
{
   S32 i,j,ss,od,sz;
   const char * name;
   const char * str;

   dumpLine("\r\nShape Hierarchy:\r\n");

   dumpLine("\r\n   Details:\r\n");

   for (i=0; i<mShape->details.size(); i++)
   {
      const TSDetail & detail = mShape->details[i];
      name = mShape->getName(detail.nameIndex);
      ss = detail.subShapeNum;
      od = detail.objectDetailNum;
      sz = (S32)detail.size;
      if (ss >= 0)
      {
         dumpLine(avar("      %s, Subtree %i, objectDetail %i, size %i\r\n",name,ss,od,sz));
      }
      else
      {
         dumpLine(avar("      %s, AutoBillboard, size %i\r\n", name, sz));
      }
   }

   dumpLine("\r\n   Subtrees:\r\n");

   for (i=0; i<mShape->subShapeFirstNode.size(); i++)
   {
      S32 a = mShape->subShapeFirstNode[i];
      S32 b = a + mShape->subShapeNumNodes[i];
      dumpLine(avar("      Subtree %i\r\n",i));

      // compute detail sizes for each subshape
      Vector<S32> detailSizes;
      for (S32 l=0;l<mShape->details.size(); l++)
      {
          if ((mShape->details[l].subShapeNum==i) || (mShape->details[l].subShapeNum==-1))
              detailSizes.push_back((S32)mShape->details[l].size);
      }

      for (j=a; j<b; j++)
      {
          const TSNode & node = mShape->nodes[j];
          // if the node has a parent, it'll get dumped via the parent
          if (node.parentIndex<0)
              dumpNode(stream,3,j,detailSizes);
      }
   }

   bool foundSkin = false;
   for (i=0; i<mShape->objects.size(); i++)
   {
      TSShape::Object& currentObject = mShape->objects[i];

      if (currentObject.nodeIndex<0) // must be a skin
      {
         if (!foundSkin)
            dumpLine("\r\n   Skins:\r\n");
         foundSkin=true;
         const char * skinName = "";
         S32 nameIndex = currentObject.nameIndex;
         if (nameIndex>=0)
            skinName = mShape->getName(nameIndex);
         dumpLine(avar("      Skin %s with following details: ",skinName));
         for (S32 num=0; num<currentObject.numMeshes; num++)
         {
            if (mShape->meshes[currentObject.startMeshIndex + num])
               dumpLine(avar(" %i",(S32)mShape->details[num].size));
         }
         dumpLine("\r\n");
      }
   }
   if (foundSkin)
      dumpLine("\r\n");

   dumpLine("\r\n   Sequences:\r\n");
   for (i = 0; i < mShape->sequences.size(); i++)
   {
      const char *name = "(none)";
      if (mShape->sequences[i].nameIndex != -1)
         name = mShape->getName(mShape->sequences[i].nameIndex);
      dumpLine(avar("      %3d: %s%s%s\r\n", i, name,
         mShape->sequences[i].isCyclic() ? " (cyclic)" : "",
         mShape->sequences[i].isBlend() ? " (blend)" : ""));
   }

   if (mShape->materialList)
   {
      TSMaterialList * ml = mShape->materialList;
      dumpLine("\r\n   Material list:\r\n");
      for (i=0; i<(S32)ml->size(); i++)
      {
         U32 flags = ml->getFlags(i);
         const String& name = ml->getMaterialName(i);
         dumpLine(avar(
            "   material #%i: '%s'%s.", i, name.c_str(),
            flags & (TSMaterialList::S_Wrap|TSMaterialList::T_Wrap) ? "" : " not tiled")
         );
         if (flags & TSMaterialList::Translucent)
         {
            if (flags & TSMaterialList::Additive)
               dumpLine("  Additive-translucent.")
            else if (flags & TSMaterialList::Subtractive)
               dumpLine("  Subtractive-translucent.")
            else
               dumpLine("  Translucent.")
         }
         dumpLine("\r\n");
      }
   }
}

<commit_msg>overgeneralised variable 'name' clarified between use-cases<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platform/platform.h"

#include "ts/tsShapeInstance.h"
#include "ts/tsMaterialList.h"
#include "core/strings/stringFunctions.h"

//-------------------------------------------------------------------------------------
// Dump shape structure:
//-------------------------------------------------------------------------------------

#define dumpLine(buffer) {str = buffer; stream.write((int)dStrlen(str),str);}

void TSShapeInstance::dumpNode(Stream & stream ,S32 level, S32 nodeIndex, Vector<S32> & detailSizes)
{
   if (nodeIndex < 0)
      return;

   // limit level to prevent overflow
   if (level > 160)
      level = 160;

   S32 i;
   const char * str;
   char space[512];
   for (i = 0; i < level*3; i++)
      space[i] = ' ';
   space[level*3] = '\0';

   const char *nodeName = "";
   const TSShape::Node & node = mShape->nodes[nodeIndex];
   if (node.nameIndex != -1)
     nodeName = mShape->getName(node.nameIndex);
   dumpLine(avar("%s%s", space, nodeName));

   // find all the objects that hang off this node...
   Vector<ObjectInstance*> objectList;
   for (i=0; i<mMeshObjects.size(); i++)
      if (mMeshObjects[i].nodeIndex == nodeIndex)
         objectList.push_back(&mMeshObjects[i]);

   if (objectList.size() == 0)
      dumpLine("\r\n");

   S32 spaceCount = -1;
   for (S32 j=0;j<objectList.size(); j++)
   {
      // should be a dynamic cast, but MSVC++ has problems with this...
      MeshObjectInstance * obj = (MeshObjectInstance *)(objectList[j]);
      if (!obj)
         continue;

      // object name
      const char *objectName = "";
      if (obj->object->nameIndex!=-1)
         objectName = mShape->getName(obj->object->nameIndex);

      // more spaces if this is the second object on this node
      if (spaceCount>0)
      {
         char buf[2048];
         dMemset(buf,' ',spaceCount);
         buf[spaceCount] = '\0';
         dumpLine(buf);
      }

      // dump object name
      dumpLine(avar(" --> Object %s with following details: ",objectName));

      // dump object detail levels
      for (S32 k=0; k<obj->object->numMeshes; k++)
      {
         S32 f = obj->object->startMeshIndex;
         if (mShape->meshes[f+k])
            dumpLine(avar(" %i",detailSizes[k]));
      }

      dumpLine("\r\n");

      // how many spaces should we prepend if we have another object on this node
      if (spaceCount<0)
         spaceCount = (S32)(dStrlen(space) + dStrlen(nodeName));

      if(spaceCount > 2000)
         spaceCount = 2000;
   }

   // search for children
   for (S32 k=nodeIndex+1; k<mShape->nodes.size(); k++)
   {
      if (mShape->nodes[k].parentIndex == nodeIndex)
         // this is our child
         dumpNode(stream, level+1, k, detailSizes);
   }
}

void TSShapeInstance::dump(Stream & stream)
{
   S32 i,j,ss,od,sz;
   const char * name;
   const char * str;

   dumpLine("\r\nShape Hierarchy:\r\n");

   dumpLine("\r\n   Details:\r\n");

   for (i=0; i<mShape->details.size(); i++)
   {
      const TSDetail & detail = mShape->details[i];
      name = mShape->getName(detail.nameIndex);
      ss = detail.subShapeNum;
      od = detail.objectDetailNum;
      sz = (S32)detail.size;
      if (ss >= 0)
      {
         dumpLine(avar("      %s, Subtree %i, objectDetail %i, size %i\r\n",name,ss,od,sz));
      }
      else
      {
         dumpLine(avar("      %s, AutoBillboard, size %i\r\n", name, sz));
      }
   }

   dumpLine("\r\n   Subtrees:\r\n");

   for (i=0; i<mShape->subShapeFirstNode.size(); i++)
   {
      S32 a = mShape->subShapeFirstNode[i];
      S32 b = a + mShape->subShapeNumNodes[i];
      dumpLine(avar("      Subtree %i\r\n",i));

      // compute detail sizes for each subshape
      Vector<S32> detailSizes;
      for (S32 l=0;l<mShape->details.size(); l++)
      {
          if ((mShape->details[l].subShapeNum==i) || (mShape->details[l].subShapeNum==-1))
              detailSizes.push_back((S32)mShape->details[l].size);
      }

      for (j=a; j<b; j++)
      {
          const TSNode & node = mShape->nodes[j];
          // if the node has a parent, it'll get dumped via the parent
          if (node.parentIndex<0)
              dumpNode(stream,3,j,detailSizes);
      }
   }

   bool foundSkin = false;
   for (i=0; i<mShape->objects.size(); i++)
   {
      TSShape::Object& currentObject = mShape->objects[i];

      if (currentObject.nodeIndex<0) // must be a skin
      {
         if (!foundSkin)
            dumpLine("\r\n   Skins:\r\n");
         foundSkin=true;
         const char * skinName = "";
         S32 nameIndex = currentObject.nameIndex;
         if (nameIndex>=0)
            skinName = mShape->getName(nameIndex);
         dumpLine(avar("      Skin %s with following details: ",skinName));
         for (S32 num=0; num<currentObject.numMeshes; num++)
         {
            if (mShape->meshes[currentObject.startMeshIndex + num])
               dumpLine(avar(" %i",(S32)mShape->details[num].size));
         }
         dumpLine("\r\n");
      }
   }
   if (foundSkin)
      dumpLine("\r\n");

   dumpLine("\r\n   Sequences:\r\n");
   for (i = 0; i < mShape->sequences.size(); i++)
   {
      const char *seqName = "(none)";
      if (mShape->sequences[i].nameIndex != -1)
		  seqName = mShape->getName(mShape->sequences[i].nameIndex);
      dumpLine(avar("      %3d: %s%s%s\r\n", i, seqName,
         mShape->sequences[i].isCyclic() ? " (cyclic)" : "",
         mShape->sequences[i].isBlend() ? " (blend)" : ""));
   }

   if (mShape->materialList)
   {
      TSMaterialList * ml = mShape->materialList;
      dumpLine("\r\n   Material list:\r\n");
      for (i=0; i<(S32)ml->size(); i++)
      {
         U32 flags = ml->getFlags(i);
         const String& matName = ml->getMaterialName(i);
         dumpLine(avar(
            "   material #%i: '%s'%s.", i, matName.c_str(),
            flags & (TSMaterialList::S_Wrap|TSMaterialList::T_Wrap) ? "" : " not tiled")
         );
         if (flags & TSMaterialList::Translucent)
         {
            if (flags & TSMaterialList::Additive)
               dumpLine("  Additive-translucent.")
            else if (flags & TSMaterialList::Subtractive)
               dumpLine("  Subtractive-translucent.")
            else
               dumpLine("  Translucent.")
         }
         dumpLine("\r\n");
      }
   }
}

<|endoftext|>


<commit_before>
#include <SimpleITK.h>

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

  if ( argc < 4 ) {
    std::cerr << "Usage: " << argv[0] << " <input> <sigma> <output>\n";
    return 1;
  }

  itk::simple::Image::Pointer image;

  itk::simple::ImageFileReader reader;
  reader.SetFilename ( std::string ( argv[1] ) );
  image = reader.Execute();

  std::cout << image->ToString() << "\n";

  itk::simple::RecursiveGaussianImageFilter gaussian;
  gaussian.SetSigma ( atof ( argv[2] ) );
  image = gaussian.Execute ( image );

  std::cout << image->ToString() << "\n";

  itk::simple::ImageFileWriter writer;
  writer.SetFilename ( std::string ( argv[3] ) );
  writer.Execute ( image );

  return 0;
}
<commit_msg>ENH: added cast in the filter pipeline to match input<commit_after>
#include <SimpleITK.h>
#include <sitkCastImageFilter.h>

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

  if ( argc < 4 ) {
    std::cerr << "Usage: " << argv[0] << " <input> <sigma> <output>\n";
    return 1;
  }

  itk::simple::Image::Pointer image;

  itk::simple::ImageFileReader reader;
  reader.SetFilename ( std::string ( argv[1] ) );
  image = reader.Execute();

  itk::simple::PixelIDValueType pixelID = image->GetPixelIDValue();

  itk::simple::RecursiveGaussianImageFilter gaussian;
  gaussian.SetSigma ( atof ( argv[2] ) );
  image = gaussian.Execute ( image );

  itk::simple::CastImageFilter caster;
  image = caster.SetOutputPixelType( pixelID ).Execute( image );

  itk::simple::ImageFileWriter writer;
  writer.SetFilename ( std::string ( argv[3] ) );
  writer.Execute ( image );

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "board.h"
#include "eventblock.h"
#include "subjectblock.h"
#include "cornerblock.h"
#include "firefridayblock.h"
#include <QTransform>
#include "localgame.h"

using namespace std;

// Constructor & Destructor
Board::Board(QGraphicsScene * scene,MainWindow * window) : QGameItem(scene,window)
{
    using namespace SubjectType;
    using namespace BlockCoords;
    //set background
    setImage(":/images/ingame/board/back_inv.png");
    blocks = new Block*[32];

    QTransform flip;
    flip.rotate(180);

    /*
     * Corner block size : 142 x 114
     * Vertical block size : 91 x 114
     * Horizontial block size : 142 x 64
     * Board size : 921 x 676
     * Horizontial Grade size: 90 x 56
     * Horizontial Grade Relative Coord: 48 x 4
     * Vertical Grade size: 84 x 69
     * Vertical Grade Relative Coord: 3 x 4
     */

    //TODO : set position and images... -ㅁ-;;

    //corner block
    blocks[0] = new CornerBlock(this,CornerType::DORM); // dorm
    blocks[0]->setImage(":/images/ingame/block/corner/Dormitory.png");
    blocks[0]->setPos(block_coord[0]);
    //CSED subject block
    blocks[1] = new SubjectBlock(this,CSED,"CSED1",45); // cse 전산 45
    blocks[1]->setImage(":/images/ingame/block/horizontial/scse1.png");
    blocks[1]->setPos(block_coord[1]);
    blocks[2] = new SubjectBlock(this,CSED,"CSED2",85); // cse 객체 85
    blocks[2]->setImage(":/images/ingame/block/horizontial/scse2.png");
    blocks[2]->setPos(block_coord[2]);
    blocks[3] = new SubjectBlock(this,CSED,"CSED3",125); // cse OS 125
    blocks[3]->setImage(":/images/ingame/block/horizontial/scse3.png");
    blocks[3]->setPos(block_coord[3]);

    //Fire block
    blocks[4] = new FireFridayBlock(this,FireFridayType::TONGZIP); //통집
    blocks[4]->setImage(":/images/ingame/block/fire/tongzip.png");
    blocks[4]->setPos(block_coord[4]);

    //ME subject block
    blocks[5] = new SubjectBlock(this,ME,"ME1",50); // me 기공개론 50
    blocks[5]->setImage(":/images/ingame/block/horizontial/sme1.png");
    blocks[5]->setPos(block_coord[5]);
    blocks[6] = new SubjectBlock(this,ME,"ME2",90); //me 열역학 90
    blocks[6]->setImage(":/images/ingame/block/horizontial/sme2.png");
    blocks[6]->setPos(block_coord[6]);
    blocks[7] = new SubjectBlock(this,ME,"ME3",130); //me 시스템설계 130
    blocks[7]->setImage(":/images/ingame/block/horizontial/sme3.png");
    blocks[7]->setPos(block_coord[7]);

    //corner block
    blocks[8] = new CornerBlock(this,CornerType::BREAKSEM); // 휴학
    blocks[8]->setImage(":/images/ingame/block/corner/gap_year.png");
    blocks[8]->setPos(block_coord[8]);

    //MATH subject block
    blocks[9] = new SubjectBlock(this,MATH,"MATH1",55); //math 응선대 55
    blocks[9]->setImage(":/images/ingame/block/normal/smath1.png");
    blocks[9]->setPos(block_coord[9]);
    blocks[10] = new SubjectBlock(this,MATH,"MATH2",95); //math 해석학 95
    blocks[10]->setImage(":/images/ingame/block/normal/smath2.png");
    blocks[10]->setPos(block_coord[10]);
    blocks[11] = new SubjectBlock(this,MATH,"MATH3",135); //math 위상수학 135
    blocks[11]->setImage(":/images/ingame/block/normal/smath3.png");
    blocks[11]->setPos(block_coord[11]);

    //Event block
    blocks[12] = new EventBlock(this,scene, window); //Event
    blocks[12]->setImage(":/images/ingame/block/Event_block.png");
    blocks[12]->setPos(block_coord[12]);

    //EE subject block
    blocks[13] = new SubjectBlock(this,EE,"EE1",60); //ee 반도체 60
    blocks[13]->setImage(":/images/ingame/block/normal/see1.png");
    blocks[13]->setPos(block_coord[13]);
    blocks[14] = new SubjectBlock(this,EE,"EE2",100); //ee 신호및시스템 100
    blocks[14]->setImage(":/images/ingame/block/normal/see2.png");
    blocks[14]->setPos(block_coord[14]);
    blocks[15] = new SubjectBlock(this,EE,"EE3",140); //ee 전자회로 140
    blocks[15]->setImage(":/images/ingame/block/normal/see3.png");
    blocks[15]->setPos(block_coord[15]);

    //Corner block
    blocks[16] = new CornerBlock(this,CornerType::PLURAL); //복수전공
    blocks[16]->setImage(":/images/ingame/block/corner/plurar_major.png");
    blocks[16]->setPos(block_coord[16]);

    //PHYS subject block
    blocks[17] = new SubjectBlock(this,PHYS,"PHYS1",65); //phys 일반물리 65
    blocks[17]->setImage(":/images/ingame/block/horizontial/sphy1.png");
    blocks[17]->setPos(block_coord[17]);

    blocks[18] = new SubjectBlock(this,PHYS,"PHYS2",105); //phys 열물리 105
    blocks[18]->setImage(":/images/ingame/block/horizontial/sphy2.png");
    blocks[18]->setPos(block_coord[18]);

    blocks[19] = new SubjectBlock(this,PHYS,"PHYS3",145); //phys 양자물리 145
    blocks[19]->setImage(":/images/ingame/block/horizontial/sphy3.png");
    blocks[19]->setPos(block_coord[19]);

    //Fire block
    blocks[20] = new FireFridayBlock(this,FireFridayType::SEOULJONGBIN); // 설종빈
    blocks[20]->setImage(":/images/ingame/block/fire/seouljongbin.png");
    blocks[20]->setPos(block_coord[20]);

    //BIO subject block
    blocks[21] = new SubjectBlock(this,BIO,"BIO1",70); //bio 일반생명 70
    blocks[21]->setImage(":/images/ingame/block/horizontial/sbio1.png");
    blocks[21]->setPos(block_coord[21]);

    blocks[22] = new SubjectBlock(this,BIO,"BIO2",110); //bio 분자생물학 110
    blocks[22]->setImage(":/images/ingame/block/horizontial/sbio2.png");
    blocks[22]->setPos(block_coord[22]);

    blocks[23] = new SubjectBlock(this,BIO,"BIO3",150); //bio 유전학 150
    blocks[23]->setImage(":/images/ingame/block/horizontial/sbio3.png");
    blocks[23]->setPos(block_coord[23]);

    //Corner block
    blocks[24] = new CornerBlock(this,CornerType::CALLTAXI); //61콜
    blocks[24]->setImage(":/images/ingame/block/corner/taxi.png");
    blocks[24]->setPos(block_coord[24]);

    //CHEM block
    blocks[25] = new SubjectBlock(this,CHEM,"CHEM1",75); //chem 일반화학 75
    blocks[25]->setImage(":/images/ingame/block/normal/schem1.png");
    blocks[25]->setPos(block_coord[25]);

    blocks[26] = new SubjectBlock(this,CHEM,"CHEM2",115); //chem 유기화학 115
    blocks[26]->setImage(":/images/ingame/block/normal/schem2.png");
    blocks[26]->setPos(block_coord[26]);

    blocks[27] = new SubjectBlock(this,CHEM,"CHEM3",155); //chem 물리화학 155
    blocks[27]->setImage(":/images/ingame/block/normal/schem3.png");
    blocks[27]->setPos(block_coord[27]);

    //Event block
    blocks[28] = new EventBlock(this,scene, window); // Event
    blocks[28]->setImage(":/images/ingame/block/Event_block2.png");
    blocks[28]->setPos(block_coord[28]);

    //IME block
    blocks[29] = new SubjectBlock(this,IME,"IME1",80); //mse 산경입문 80
    blocks[29]->setImage(":/images/ingame/block/normal/sime1.png");
    blocks[29]->setPos(block_coord[29]);

    blocks[30] = new SubjectBlock(this,IME,"IME2",120); //mse 제품생산공정 120
    blocks[30]->setImage(":/images/ingame/block/normal/sime2.png");
    blocks[30]->setPos(block_coord[30]);

    blocks[31] = new SubjectBlock(this,IME,"IME3",160); //mse 품질공학 160
    blocks[31]->setImage(":/images/ingame/block/normal/sime3.png");
    blocks[31]->setPos(block_coord[31]);

    for(int i=0; i<32; i++)
    {
        blocks[i]->setPosition(i);
        connect(blocks[i],SIGNAL(blockClicked(Block*)),LocalGame::getInst(),SLOT(blockEvent(Block*)));
    }
}

void Board::diceRolled(int dice, bool is_double){
    //do something if is_double
    if(is_double){
        QGameItem * double_img = new QGameItem(this);
        double_img->setImage(":/images/ingame/double.png");
    }
}

Board::~Board()
{
    for(int i=0; i<32; i++)
        delete blocks[i];
    delete[] blocks;
}

// Methods
int Board::getLength() const
{
    return length;
}

Block* Board::getBlock(int position) const
{
    return blocks[position];
}

void Board::enter(Player* player)
{
    blocks[player->getPosition()]->enter(player);
}

namespace BlockCoords {
    const int corner_w = 142;
    const int corner_h = 114;
    const int hblock_w = 91;
//const int hblock_h = 114; //not used
//const int vblock_w = 142; //not used
    const int vblock_h = 64;

    QPointF block_coord[32] = {
    QPointF(0,corner_h + vblock_h * 7),
    QPointF(0,corner_h + vblock_h * 6),
    QPointF(0,corner_h + vblock_h * 5),
    QPointF(0,corner_h + vblock_h * 4),
    QPointF(0,corner_h + vblock_h * 3),
    QPointF(0,corner_h + vblock_h * 2),
    QPointF(0,corner_h + vblock_h * 1),
    QPointF(0,corner_h + vblock_h * 0),
    QPointF(0,0),
    QPointF(corner_w + hblock_w * 0,0),
    QPointF(corner_w + hblock_w * 1,0),
    QPointF(corner_w + hblock_w * 2,0),
    QPointF(corner_w + hblock_w * 3,0),
    QPointF(corner_w + hblock_w * 4,0),
    QPointF(corner_w + hblock_w * 5,0),
    QPointF(corner_w + hblock_w * 6,0),
    QPointF(corner_w + hblock_w * 7,0),
    QPointF(corner_w + hblock_w * 7, corner_h),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 1),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 2),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 3),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 4),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 5),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 6),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 6, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 5, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 4, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 3, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 2, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 1, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 0, corner_h + vblock_h * 7)
    };

    QPointF corner_coord[4] = {
        block_coord[0],
        block_coord[8],
        block_coord[16],
        block_coord[24],
    };
}
<commit_msg>Board: Subject Name Filled<commit_after>#include <iostream>
#include "board.h"
#include "eventblock.h"
#include "subjectblock.h"
#include "cornerblock.h"
#include "firefridayblock.h"
#include <QTransform>
#include "localgame.h"

using namespace std;

// Constructor & Destructor
Board::Board(QGraphicsScene * scene,MainWindow * window) : QGameItem(scene,window)
{
    using namespace SubjectType;
    using namespace BlockCoords;
    //set background
    setImage(":/images/ingame/board/back_inv.png");
    blocks = new Block*[32];

    QTransform flip;
    flip.rotate(180);

    /*
     * Corner block size : 142 x 114
     * Vertical block size : 91 x 114
     * Horizontial block size : 142 x 64
     * Board size : 921 x 676
     * Horizontial Grade size: 90 x 56
     * Horizontial Grade Relative Coord: 48 x 4
     * Vertical Grade size: 84 x 69
     * Vertical Grade Relative Coord: 3 x 4
     */

    //TODO : set position and images... -ㅁ-;;

    //corner block
    blocks[0] = new CornerBlock(this,CornerType::DORM); // dorm
    blocks[0]->setImage(":/images/ingame/block/corner/Dormitory.png");
    blocks[0]->setPos(block_coord[0]);
    //CSED subject block
    blocks[1] = new SubjectBlock(this,CSED,"프로그래밍과 문제해결",45); // cse 전산 45
    blocks[1]->setImage(":/images/ingame/block/horizontial/scse1.png");
    blocks[1]->setPos(block_coord[1]);
    blocks[2] = new SubjectBlock(this,CSED,"객체지향프로그래밍",85); // cse 객체 85
    blocks[2]->setImage(":/images/ingame/block/horizontial/scse2.png");
    blocks[2]->setPos(block_coord[2]);
    blocks[3] = new SubjectBlock(this,CSED,"운영체제",125); // cse OS 125
    blocks[3]->setImage(":/images/ingame/block/horizontial/scse3.png");
    blocks[3]->setPos(block_coord[3]);

    //Fire block
    blocks[4] = new FireFridayBlock(this,FireFridayType::TONGZIP); //통집
    blocks[4]->setImage(":/images/ingame/block/fire/tongzip.png");
    blocks[4]->setPos(block_coord[4]);

    //ME subject block
    blocks[5] = new SubjectBlock(this,ME,"기계공학개론",50); // me 기공개론 50
    blocks[5]->setImage(":/images/ingame/block/horizontial/sme1.png");
    blocks[5]->setPos(block_coord[5]);
    blocks[6] = new SubjectBlock(this,ME,"열역학",90); //me 열역학 90
    blocks[6]->setImage(":/images/ingame/block/horizontial/sme2.png");
    blocks[6]->setPos(block_coord[6]);
    blocks[7] = new SubjectBlock(this,ME,"시스템설계",130); //me 시스템설계 130
    blocks[7]->setImage(":/images/ingame/block/horizontial/sme3.png");
    blocks[7]->setPos(block_coord[7]);

    //corner block
    blocks[8] = new CornerBlock(this,CornerType::BREAKSEM); // 휴학
    blocks[8]->setImage(":/images/ingame/block/corner/gap_year.png");
    blocks[8]->setPos(block_coord[8]);

    //MATH subject block
    blocks[9] = new SubjectBlock(this,MATH,"응용선형대수",55); //math 응선대 55
    blocks[9]->setImage(":/images/ingame/block/normal/smath1.png");
    blocks[9]->setPos(block_coord[9]);
    blocks[10] = new SubjectBlock(this,MATH,"해석학",95); //math 해석학 95
    blocks[10]->setImage(":/images/ingame/block/normal/smath2.png");
    blocks[10]->setPos(block_coord[10]);
    blocks[11] = new SubjectBlock(this,MATH,"위상수학",135); //math 위상수학 135
    blocks[11]->setImage(":/images/ingame/block/normal/smath3.png");
    blocks[11]->setPos(block_coord[11]);

    //Event block
    blocks[12] = new EventBlock(this,scene, window); //Event
    blocks[12]->setImage(":/images/ingame/block/Event_block.png");
    blocks[12]->setPos(block_coord[12]);

    //EE subject block
    blocks[13] = new SubjectBlock(this,EE,"회로이론",60); //ee 회로이론 60
    blocks[13]->setImage(":/images/ingame/block/normal/see1.png");
    blocks[13]->setPos(block_coord[13]);
    blocks[14] = new SubjectBlock(this,EE,"반도체",100); //ee 반도체 100
    blocks[14]->setImage(":/images/ingame/block/normal/see2.png");
    blocks[14]->setPos(block_coord[14]);
    blocks[15] = new SubjectBlock(this,EE,"신호 및 시스",140); //ee 신호및시스템 140
    blocks[15]->setImage(":/images/ingame/block/normal/see3.png");
    blocks[15]->setPos(block_coord[15]);

    //Corner block
    blocks[16] = new CornerBlock(this,CornerType::PLURAL); //복수전공
    blocks[16]->setImage(":/images/ingame/block/corner/plurar_major.png");
    blocks[16]->setPos(block_coord[16]);

    //PHYS subject block
    blocks[17] = new SubjectBlock(this,PHYS,"일반물리",65); //phys 일반물리 65
    blocks[17]->setImage(":/images/ingame/block/horizontial/sphy1.png");
    blocks[17]->setPos(block_coord[17]);

    blocks[18] = new SubjectBlock(this,PHYS,"열물리",105); //phys 열물리 105
    blocks[18]->setImage(":/images/ingame/block/horizontial/sphy2.png");
    blocks[18]->setPos(block_coord[18]);

    blocks[19] = new SubjectBlock(this,PHYS,"양자물리",145); //phys 양자물리 145
    blocks[19]->setImage(":/images/ingame/block/horizontial/sphy3.png");
    blocks[19]->setPos(block_coord[19]);

    //Fire block
    blocks[20] = new FireFridayBlock(this,FireFridayType::SEOULJONGBIN); // 설종빈
    blocks[20]->setImage(":/images/ingame/block/fire/seouljongbin.png");
    blocks[20]->setPos(block_coord[20]);

    //BIO subject block
    blocks[21] = new SubjectBlock(this,BIO,"일반생명",70); //bio 일반생명 70
    blocks[21]->setImage(":/images/ingame/block/horizontial/sbio1.png");
    blocks[21]->setPos(block_coord[21]);

    blocks[22] = new SubjectBlock(this,BIO,"분자생물학",110); //bio 분자생물학 110
    blocks[22]->setImage(":/images/ingame/block/horizontial/sbio2.png");
    blocks[22]->setPos(block_coord[22]);

    blocks[23] = new SubjectBlock(this,BIO,"유전학",150); //bio 유전학 150
    blocks[23]->setImage(":/images/ingame/block/horizontial/sbio3.png");
    blocks[23]->setPos(block_coord[23]);

    //Corner block
    blocks[24] = new CornerBlock(this,CornerType::CALLTAXI); //61콜
    blocks[24]->setImage(":/images/ingame/block/corner/taxi.png");
    blocks[24]->setPos(block_coord[24]);

    //CHEM block
    blocks[25] = new SubjectBlock(this,CHEM,"일반화학",75); //chem 일반화학 75
    blocks[25]->setImage(":/images/ingame/block/normal/schem1.png");
    blocks[25]->setPos(block_coord[25]);

    blocks[26] = new SubjectBlock(this,CHEM,"유기화학",115); //chem 유기화학 115
    blocks[26]->setImage(":/images/ingame/block/normal/schem2.png");
    blocks[26]->setPos(block_coord[26]);

    blocks[27] = new SubjectBlock(this,CHEM,"물리화확",155); //chem 물리화학 155
    blocks[27]->setImage(":/images/ingame/block/normal/schem3.png");
    blocks[27]->setPos(block_coord[27]);

    //Event block
    blocks[28] = new EventBlock(this,scene, window); // Event
    blocks[28]->setImage(":/images/ingame/block/Event_block2.png");
    blocks[28]->setPos(block_coord[28]);

    //IME block
    blocks[29] = new SubjectBlock(this,IME,"IME1",80); //mse 산경입문 80
    blocks[29]->setImage(":/images/ingame/block/normal/sime1.png");
    blocks[29]->setPos(block_coord[29]);

    blocks[30] = new SubjectBlock(this,IME,"IME2",120); //mse 제품생산공정 120
    blocks[30]->setImage(":/images/ingame/block/normal/sime2.png");
    blocks[30]->setPos(block_coord[30]);

    blocks[31] = new SubjectBlock(this,IME,"IME3",160); //mse 품질공학 160
    blocks[31]->setImage(":/images/ingame/block/normal/sime3.png");
    blocks[31]->setPos(block_coord[31]);

    for(int i=0; i<32; i++)
    {
        blocks[i]->setPosition(i);
        connect(blocks[i],SIGNAL(blockClicked(Block*)),LocalGame::getInst(),SLOT(blockEvent(Block*)));
    }
}

void Board::diceRolled(int dice, bool is_double){
    //do something if is_double
    if(is_double){
        QGameItem * double_img = new QGameItem(this);
        double_img->setImage(":/images/ingame/double.png");
    }
}

Board::~Board()
{
    for(int i=0; i<32; i++)
        delete blocks[i];
    delete[] blocks;
}

// Methods
int Board::getLength() const
{
    return length;
}

Block* Board::getBlock(int position) const
{
    return blocks[position];
}

void Board::enter(Player* player)
{
    blocks[player->getPosition()]->enter(player);
}

namespace BlockCoords {
    const int corner_w = 142;
    const int corner_h = 114;
    const int hblock_w = 91;
//const int hblock_h = 114; //not used
//const int vblock_w = 142; //not used
    const int vblock_h = 64;

    QPointF block_coord[32] = {
    QPointF(0,corner_h + vblock_h * 7),
    QPointF(0,corner_h + vblock_h * 6),
    QPointF(0,corner_h + vblock_h * 5),
    QPointF(0,corner_h + vblock_h * 4),
    QPointF(0,corner_h + vblock_h * 3),
    QPointF(0,corner_h + vblock_h * 2),
    QPointF(0,corner_h + vblock_h * 1),
    QPointF(0,corner_h + vblock_h * 0),
    QPointF(0,0),
    QPointF(corner_w + hblock_w * 0,0),
    QPointF(corner_w + hblock_w * 1,0),
    QPointF(corner_w + hblock_w * 2,0),
    QPointF(corner_w + hblock_w * 3,0),
    QPointF(corner_w + hblock_w * 4,0),
    QPointF(corner_w + hblock_w * 5,0),
    QPointF(corner_w + hblock_w * 6,0),
    QPointF(corner_w + hblock_w * 7,0),
    QPointF(corner_w + hblock_w * 7, corner_h),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 1),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 2),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 3),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 4),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 5),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 6),
    QPointF(corner_w + hblock_w * 7, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 6, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 5, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 4, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 3, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 2, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 1, corner_h + vblock_h * 7),
    QPointF(corner_w + hblock_w * 0, corner_h + vblock_h * 7)
    };

    QPointF corner_coord[4] = {
        block_coord[0],
        block_coord[8],
        block_coord[16],
        block_coord[24],
    };
}
<|endoftext|>