<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: stack64.cc,v 1.32 2007/12/20 20:58:37 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR

#if BX_SUPPORT_X86_64

void BX_CPU_C::POP_EqM(bxInstruction_c *i)
{
  BX_CPU_THIS_PTR speculative_rsp = 1;
  BX_CPU_THIS_PTR prev_rsp = RSP;

  Bit64u val64 = pop_64();

  // Note: there is one little weirdism here.  It is possible to use
  // RSP in the modrm addressing. If used, the value of RSP after the
  // pop is used to calculate the address.
  if (i->rm()==4 && i->sibBase()==4) {
    // call method on BX_CPU_C object
    BX_CPU_CALL_METHODR (i->ResolveModrm, (i));
  }
  write_virtual_qword(i->seg(), RMAddr(i), val64);

  BX_CPU_THIS_PTR speculative_rsp = 0;
}

void BX_CPU_C::POP_EqR(bxInstruction_c *i)
{
  BX_WRITE_64BIT_REG(i->rm(), pop_64());
}

void BX_CPU_C::PUSH_RRX(bxInstruction_c *i)
{
  push_64(BX_READ_64BIT_REG(i->opcodeReg()));
}

void BX_CPU_C::POP_RRX(bxInstruction_c *i)
{
  BX_WRITE_64BIT_REG(i->opcodeReg(), pop_64());
}

void BX_CPU_C::PUSH64_FS(bxInstruction_c *i)
{
  push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS].selector.value);
}

void BX_CPU_C::PUSH64_GS(bxInstruction_c *i)
{
  push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS].selector.value);
}

void BX_CPU_C::POP64_FS(bxInstruction_c *i)
{
  // this way is faster and RSP safe
  Bit64u fs = read_virtual_qword(BX_SEG_REG_SS, RSP);
  load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS], (Bit16u) fs);
  RSP += 8;
}

void BX_CPU_C::POP64_GS(bxInstruction_c *i)
{
  // this way is faster and RSP safe
  Bit64u gs = read_virtual_qword(BX_SEG_REG_SS, RSP);
  load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS], (Bit16u) gs);
  RSP += 8;
}

void BX_CPU_C::PUSH64_Id(bxInstruction_c *i)
{
  Bit64u imm64 = (Bit32s) i->Id();
  push_64(imm64);
}

void BX_CPU_C::PUSH_EqM(bxInstruction_c *i)
{
  Bit64u op1_64 = read_virtual_qword(i->seg(), RMAddr(i));

  push_64(op1_64);
}

void BX_CPU_C::PUSH_EqR(bxInstruction_c *i)
{
  push_64(BX_READ_64BIT_REG(i->rm()));
}

void BX_CPU_C::ENTER64_IwIb(bxInstruction_c *i)
{
  Bit8u level = i->Ib2();
  level &= 0x1F;
  Bit64u bytes_to_push = 8 + level*8 + i->Iw();

  BX_CPU_THIS_PTR speculative_rsp = 1;
  BX_CPU_THIS_PTR prev_rsp = RSP;

  push_64(RBP);

  Bit64u frame_ptr64 = RSP;

  if (level > 0) {
    /* do level-1 times */
    while (--level) {
      Bit64u temp64;

      RBP -= 8;
      temp64 = read_virtual_qword(BX_SEG_REG_SS, RBP);
      RSP -= 8;
      write_virtual_qword(BX_SEG_REG_SS, RSP, temp64);
    } /* while (--level) */

    /* push(frame pointer) */
    RSP -= 8;
    write_virtual_qword(BX_SEG_REG_SS, RSP, frame_ptr64);
  } /* if (level > 0) ... */

  BX_CPU_THIS_PTR speculative_rsp = 0;

  RBP = frame_ptr64;
  RSP -= i->Iw();
}

void BX_CPU_C::LEAVE64(bxInstruction_c *i)
{
  // restore frame pointer
  Bit64u temp64 = read_virtual_qword(BX_SEG_REG_SS, RBP);
  RSP = RBP + 8;
  RBP = temp64;
}

#endif /* if BX_SUPPORT_X86_64 */
<commit_msg>removed unused variable<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: stack64.cc,v 1.33 2008/01/01 18:01:39 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR

#if BX_SUPPORT_X86_64

void BX_CPU_C::POP_EqM(bxInstruction_c *i)
{
  BX_CPU_THIS_PTR speculative_rsp = 1;
  BX_CPU_THIS_PTR prev_rsp = RSP;

  Bit64u val64 = pop_64();

  // Note: there is one little weirdism here.  It is possible to use
  // RSP in the modrm addressing. If used, the value of RSP after the
  // pop is used to calculate the address.
  if (i->rm()==4 && i->sibBase()==4) {
    // call method on BX_CPU_C object
    BX_CPU_CALL_METHODR (i->ResolveModrm, (i));
  }
  write_virtual_qword(i->seg(), RMAddr(i), val64);

  BX_CPU_THIS_PTR speculative_rsp = 0;
}

void BX_CPU_C::POP_EqR(bxInstruction_c *i)
{
  BX_WRITE_64BIT_REG(i->rm(), pop_64());
}

void BX_CPU_C::PUSH_RRX(bxInstruction_c *i)
{
  push_64(BX_READ_64BIT_REG(i->opcodeReg()));
}

void BX_CPU_C::POP_RRX(bxInstruction_c *i)
{
  BX_WRITE_64BIT_REG(i->opcodeReg(), pop_64());
}

void BX_CPU_C::PUSH64_FS(bxInstruction_c *i)
{
  push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS].selector.value);
}

void BX_CPU_C::PUSH64_GS(bxInstruction_c *i)
{
  push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS].selector.value);
}

void BX_CPU_C::POP64_FS(bxInstruction_c *i)
{
  // this way is faster and RSP safe
  Bit64u fs = read_virtual_qword(BX_SEG_REG_SS, RSP);
  load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS], (Bit16u) fs);
  RSP += 8;
}

void BX_CPU_C::POP64_GS(bxInstruction_c *i)
{
  // this way is faster and RSP safe
  Bit64u gs = read_virtual_qword(BX_SEG_REG_SS, RSP);
  load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS], (Bit16u) gs);
  RSP += 8;
}

void BX_CPU_C::PUSH64_Id(bxInstruction_c *i)
{
  Bit64u imm64 = (Bit32s) i->Id();
  push_64(imm64);
}

void BX_CPU_C::PUSH_EqM(bxInstruction_c *i)
{
  Bit64u op1_64 = read_virtual_qword(i->seg(), RMAddr(i));

  push_64(op1_64);
}

void BX_CPU_C::PUSH_EqR(bxInstruction_c *i)
{
  push_64(BX_READ_64BIT_REG(i->rm()));
}

void BX_CPU_C::ENTER64_IwIb(bxInstruction_c *i)
{
  Bit8u level = i->Ib2();
  level &= 0x1F;

  BX_CPU_THIS_PTR speculative_rsp = 1;
  BX_CPU_THIS_PTR prev_rsp = RSP;

  push_64(RBP);

  Bit64u frame_ptr64 = RSP;

  if (level > 0) {
    /* do level-1 times */
    while (--level) {
      Bit64u temp64;

      RBP -= 8;
      temp64 = read_virtual_qword(BX_SEG_REG_SS, RBP);
      RSP -= 8;
      write_virtual_qword(BX_SEG_REG_SS, RSP, temp64);
    } /* while (--level) */

    /* push(frame pointer) */
    RSP -= 8;
    write_virtual_qword(BX_SEG_REG_SS, RSP, frame_ptr64);
  } /* if (level > 0) ... */

  BX_CPU_THIS_PTR speculative_rsp = 0;

  RBP = frame_ptr64;
  RSP -= i->Iw();
}

void BX_CPU_C::LEAVE64(bxInstruction_c *i)
{
  // restore frame pointer
  Bit64u temp64 = read_virtual_qword(BX_SEG_REG_SS, RBP);
  RSP = RBP + 8;
  RBP = temp64;
}

#endif /* if BX_SUPPORT_X86_64 */
<|endoftext|>


<commit_before>/*!
 * @file RPU.cpp
 * @author James Johns
 */
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#include <queue>
#include <iostream>

#include <RPU.h>
#include <KeypadDevice.h>
#include <KeyboardDevice.h>
#include <NCursesDisplay.h>
#include <Menu.hpp>
#include <VLCAudioPlayer.h>
#include <CDDWebApi.h>

/*! RPU::RPU(void *(*audioThreadEntry)(void *), void *(*ioThreadEntry)(void *))
 * @author James Johns
 * @brief RPU constructor
 *
 * @param[in] audioThreadEntry function pointer to auidio thread start point
 * @param[in] ioThreadEntry function pointer to io thread start point
 */
RPU::RPU(void *(*audioThreadEntry)(void *), void *(*ioThreadEntry)(void *))
{
	char *ipaddr = NULL;
	std::vector<char *> *addresses = getIPAddress();
	for (std::vector<char *>::iterator it = addresses->begin(); it != addresses->end(); it++) {
		if (strncmp("127", *it, 3) != 0 && ipaddr == NULL)
			ipaddr = *it;
		else
			delete *it;
	}
	delete addresses;
	printf("%s\n", ipaddr);
	player = new VLCAudioPlayer(ipaddr);
	cddapi = new CDDWebApi(ipaddr);
	delete ipaddr;

	mainMenu = new Menu();
	mainMenu->addMenuItem("Enter Exhibit");
	mainMenu->addMenuItem("Change Language");
	mainMenu->addMenuItem("Change Knowledge Level");

	/* Create input device as a keypad. If this fails, default to keyboard instead */
	input = new KeypadDevice();
	if (input->isConnected() == false) { // if keypad is not connected, fallback to keyboard
		delete input;
		input = new KeyboardDevice();
	}
	state = LOGIN_PROMPT;

	// connect to NCurses display by default
	display = new NCursesDisplay();
	display->setErrorString("Please enter PIN to unlock");

	/*! Event queue must be initialised before threads as they depend on sending events to RPU */
	eventQueue = new std::queue<Event *>();

	/* Create threads */
	if (pthread_create(&audioThread, NULL, audioThreadEntry, player) != 0) {
		perror("Could not create audio thread");
	}

	if (pthread_create(&ioThread, NULL, ioThreadEntry, this) != 0) {
		perror("Could not create audio thread");
	}
	running = true;
}

/*! RPU::~RPU()
 * @author James Johns
 * @brief RPU destructor
 *
 */
RPU::~RPU()
{
	running = false;
	player->stop();
	pthread_join(ioThread, NULL);
	pthread_join(audioThread, NULL);
	delete player;
	delete input;
	delete display;
	delete cddapi;
}

/*! RPU::tick()
 * @author James Johns
 * @brief RPU update tick
 *
 * Call iteratively to allow RPU to execute next action.
 * Handles events sent to the RPU, such as input, stream requests etc.
 */
void RPU::tick()
{
	//Checks for incoming broadcast. Mutes regular streaming
	//Returns bool; true if broadcasting, false if not
	player->listen();

	Event *evt = getEvent();
	do {
		if (evt != NULL) {
			if (evt->getType() == Event::QUIT) {
				running = false;
			}
		}
		switch (state) {
		case LOGIN_PROMPT:
			loginPrompt(evt);
			break;
		case DISPLAY_MENU:
			displayMenu(evt);
			break;
		case SELECT_LANGUAGE:
			selectLanguage(evt);
			break;
		case SELECT_KNOWLEDGE:
			selectKnowledge(evt);
			break;
		default:
			break;
		}

		if (evt != NULL)
			delete evt;
		evt = getEvent();
	} while (evt != NULL);
}

/*! RPU::sendEvent(Event *evt)
 * @author James Johns
 * @brief Send Event to RPU
 *
 * @param[in] evt Event to place in event queue
 */
void RPU::sendEvent(Event *evt)
{
	eventQueue->push(evt);
}

/*! RPU::getEvent()
 * @author James Johns
 * @brief Get event in event queue
 *
 * @return Event at front of event queue. Returns NULL if queue is empty.
 */
Event *RPU::getEvent()
{
	Event *evt = NULL;
	if (!eventQueue->empty()) {
		evt = eventQueue->front();
		eventQueue->pop();
	}
	return evt;
}

/*! RPU::getIPAddress()
 * @author James Johns
 * @brief Find the device's current IP address
 *
 * @return List of strings containing IP addresses that the device is associated with
 */
std::vector<char *> *RPU::getIPAddress()
{
	struct ifaddrs *ifAddrs = NULL, *curAddr = NULL;
	void *tmpAddr = NULL;
	char *tmpStr = NULL;
	std::vector<char *> *toRet = new std::vector<char *>;

	getifaddrs(&ifAddrs);

	for (curAddr = ifAddrs; curAddr != NULL; curAddr = curAddr->ifa_next) {
		if (!curAddr->ifa_addr)
			continue;

		if (curAddr->ifa_addr->sa_family == AF_INET) {
			tmpAddr = &((struct sockaddr_in *)curAddr->ifa_addr)->sin_addr;
			tmpStr = new char[INET_ADDRSTRLEN];
			inet_ntop(AF_INET, tmpAddr, tmpStr, INET_ADDRSTRLEN);
			toRet->push_back(tmpStr);

		} else {
			continue;
		}
	}

	return toRet;
}

void RPU::loginPrompt(Event *evt)
{
	static bool entered = false;

	if (entered == false) {
		display->setErrorString("Please enter PIN to unlock");
		entered = true;
	}

	if (evt == NULL)
		return;

	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'q':
			running = false;
			break;
		case 'c':/*!< Enter key */
			/* enter selected menu entry */
			//if (cddapi->login(numberInput.c_str()) == 0) {
		  if(1) {
		  state = DISPLAY_MENU;
				display->setMenuString(mainMenu->getCurrentMenuItem());
				display->setErrorString(NULL);
				entered = false;
			} else {
				display->setErrorString(cddapi->getLastSentMessage().c_str());
			}
			break;
		case '1' ... '9':
			/* capture PIN input */
			numberInput.push_back(*(char *)evt->getArguments());
			if (numberInput.length() > 4) // pop data from front of string to reduce to 4 character string
				numberInput.erase(0, numberInput.length() - 4);
			break;
		case 'p':/*!< play */
		case 'r':/*!< rewind */
		case 'f':/*!< Fast Forward */
		case 'w':/*!< Up key */
		case 's':/*!< Down key */
		default:
			/* ignored */
			break;
		}
		break;
	default:
		break;
	}
}

void RPU::displayMenu(Event *evt)
{
	static bool entered = false;

	if (entered == false) {
		display->setMenuString(mainMenu->getCurrentMenuItem());
		entered = true;
	}

	if (evt == NULL)
		return;

	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'p':
			if (player != NULL) {
				player->playpause();
				display->setPlaybackString(((player->isPlaying()) ? "Play" : "Pause"));
			}
			break;
		case 'r':
		  if (player != NULL) {
				player->rewind();
			}
			break;
		case 'f': /*!< Fast Forward */
		  if (player != NULL) {
		    player->fastForward();
		  }
			break;
		case 'q':
			state = LOGIN_PROMPT;
			display->setErrorString("Please enter PIN to unlock");
			display->setMenuString(NULL);
			display->setPlaybackString(NULL);
			display->setTrackInfoString(NULL);
			break;
		case 'w':/*!< Up key */
			mainMenu->up();
			display->setMenuString(mainMenu->getCurrentMenuItem());
			break;
		case 's':/*!< Down key */
			mainMenu->down();
			display->setMenuString(mainMenu->getCurrentMenuItem());
			break;
		case 'c':/*!< Enter (continue) key */
			/* Enter selected menu entry */
			if (mainMenu->getCurrentSelected() == 0) {
				display->setErrorString(numberInput.c_str());
				cddapi->requestAudioStream(numberInput.c_str());
				player->play();
			} else if (mainMenu->getCurrentSelected() == 1) {
				state = SELECT_LANGUAGE;
				entered = false;
			} else if (mainMenu->getCurrentSelected() == 2) {
				state = SELECT_KNOWLEDGE;
				entered = false;
			}
			break;
		case '1' ... '9':
			numberInput.push_back(*(char *)evt->getArguments());
			if (numberInput.length() > 4) // pop data from front of string to reduce to 4 character string
				numberInput.erase(0, numberInput.length() - 4);
			break;
		default:
			break;
		}
		break;
	default:
		break;
	}
}

void RPU::selectLanguage(Event *evt)
{
	static bool entered = false;
	static int language = 0;
	char *langString;
	int tmpLang = language;
	std::vector<std::string> supportedLanguages = cddapi->getSupportedLanguages();

	if (entered == false) {
		do {
			language++;
			langString = (char *) supportedLanguages[language].c_str();
		} while (langString == NULL && language < supportedLanguages.size());
		if (language >= supportedLanguages.size())
			language = tmpLang;
		display->setMenuString(supportedLanguages[language].c_str());
		entered = true;
	}

	if (evt == NULL)
		return;

	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'p':
			if (player != NULL) {
				player->playpause();
				display->setPlaybackString((char *)((player->isPlaying()) ? "Play" : "Pause"));
			}
			break;
		case 'r':
			if (player != NULL) {
				player->rewind();
			}
			break;
		case 'f': /*!< Fast Forward */
		  if (player != NULL) {
		    player->fastForward();
		  }
			break;
		case 'q':
			state = DISPLAY_MENU;
			entered = false;
			break;
		case 'w':/*!< Up key */
			do {
				language++;
				langString = (char *) supportedLanguages[language].c_str();
			} while (langString == NULL && language < supportedLanguages.size());
			if (language >= supportedLanguages.size())
				language = tmpLang;
			display->setMenuString(supportedLanguages[language].c_str());
			break;
		case 's':/*!< Down key */
			do {
				language--;
				langString = (char *) supportedLanguages[language].c_str();
			} while (langString == NULL && language > 0);
			if (language < 0)
				language = tmpLang;
			display->setMenuString(supportedLanguages[language].c_str());
			break;
		case 'c':/*!< Enter key */
			cddapi->changeLanguage(language);
			state = DISPLAY_MENU;
			entered = false;
			break;
		case '1' ... '9':
		default:
			break;
		}
		break;
	default:
		break;
	}
}

void RPU::selectKnowledge(Event *evt)
{
	static bool entered = false;
	static int knowledge = 0;
	char *knowString;
	int tmpKnow = knowledge;
	std::vector<std::string> supportedKnowledgeLevels = cddapi->getSupportedKnowledgeLevels();

	if (entered == false) {
		do {
			knowledge++;
			knowString = (char *) supportedKnowledgeLevels[knowledge].c_str();
		} while (knowString == NULL && knowledge < supportedKnowledgeLevels.size());
		if (knowledge >= supportedKnowledgeLevels.size())
			knowledge = tmpKnow;
		display->setMenuString(supportedKnowledgeLevels[knowledge].c_str());
		entered = true;
	}

	if (evt == NULL)
		return;

	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'p':
			if (player != NULL) {
				player->playpause();
				display->setPlaybackString((char *)((player->isPlaying()) ? "Play" : "Pause"));
			}
			break;
		case 'r':
			if (player != NULL) {
				player->rewind();
			}
			break;
		case 'f':/*!< Fast Forward */
		  if(player != NULL) {
		    player->fastForward();
		  }
			break;
		case 'q':
			state = DISPLAY_MENU;
			entered = false;
			break;
		case 'c':/*!< Enter key */
			cddapi->changeKnowledgeLevel(knowledge);
			state = DISPLAY_MENU;
			entered = false;
			break;
		case 'w':/*!< Up key */
			do {
				knowledge++;
				knowString = (char *) supportedKnowledgeLevels[knowledge].c_str();
			} while (knowString == NULL && knowledge < supportedKnowledgeLevels.size());
			if (knowledge >= supportedKnowledgeLevels.size())
				knowledge = tmpKnow;
			display->setMenuString(supportedKnowledgeLevels[knowledge].c_str());
			break;
		case 's':/*!< Down key */
			do {
				knowledge--;
				knowString = (char *) supportedKnowledgeLevels[knowledge].c_str();
			} while (knowString == NULL && knowledge >= 0);
			if (knowledge < 0)
				knowledge = tmpKnow;
			display->setMenuString(supportedKnowledgeLevels[knowledge].c_str());
			break;
		case '1' ... '9':
		default:
			break;
		}
		break;
	default:
		break;
	}
}

void RPU::requestStream(Event *evt)
{
	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'p':
			if (player != NULL) {
				player->playpause();
				display->setPlaybackString((char *)((player->isPlaying()) ? "Play" : "Pause"));
			}
			break;
		case 'r':
			if (player != NULL) {
				player->rewind();
			}
			break;
		case 'f':/*!< Fast Forward */
		  if (player != NULL) {
		    player->fastForward();
		  }
			break;
		case 'q': /* cancel key - return to menu */
			state = DISPLAY_MENU;
			break;
		case 'c':/*!< Enter key */
			/* TODO: Request stream using last 4 digits input */
			break;
		case '1' ... '9':
			/* TODO: Capture Exhibit ID input */
			break;
		case 'w':/*!< Up key */
		case 's':/*!< Down key */
		default:
			// Unused
			break;
		}
		break;
	default:
		break;
	}
}
<commit_msg>Revert RPU.cpp<commit_after>/*!
 * @file RPU.cpp
 * @author James Johns
 */
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#include <queue>
#include <iostream>

#include <RPU.h>
#include <KeypadDevice.h>
#include <KeyboardDevice.h>
#include <NCursesDisplay.h>
#include <Menu.hpp>
#include <VLCAudioPlayer.h>
#include <CDDWebApi.h>

/*! RPU::RPU(void *(*audioThreadEntry)(void *), void *(*ioThreadEntry)(void *))
 * @author James Johns
 * @brief RPU constructor
 *
 * @param[in] audioThreadEntry function pointer to auidio thread start point
 * @param[in] ioThreadEntry function pointer to io thread start point
 */
RPU::RPU(void *(*audioThreadEntry)(void *), void *(*ioThreadEntry)(void *))
{
	char *ipaddr = NULL;
	std::vector<char *> *addresses = getIPAddress();
	for (std::vector<char *>::iterator it = addresses->begin(); it != addresses->end(); it++) {
		if (strncmp("127", *it, 3) != 0 && ipaddr == NULL)
			ipaddr = *it;
		else
			delete *it;
	}
	delete addresses;
	printf("%s\n", ipaddr);
	player = new VLCAudioPlayer(ipaddr);
	cddapi = new CDDWebApi(ipaddr);
	delete ipaddr;

	mainMenu = new Menu();
	mainMenu->addMenuItem("Enter Exhibit");
	mainMenu->addMenuItem("Change Language");
	mainMenu->addMenuItem("Change Knowledge Level");

	/* Create input device as a keypad. If this fails, default to keyboard instead */
	input = new KeypadDevice();
	if (input->isConnected() == false) { // if keypad is not connected, fallback to keyboard
		delete input;
		input = new KeyboardDevice();
	}
	state = LOGIN_PROMPT;

	// connect to NCurses display by default
	display = new NCursesDisplay();
	display->setErrorString("Please enter PIN to unlock");

	/*! Event queue must be initialised before threads as they depend on sending events to RPU */
	eventQueue = new std::queue<Event *>();

	/* Create threads */
	if (pthread_create(&audioThread, NULL, audioThreadEntry, player) != 0) {
		perror("Could not create audio thread");
	}

	if (pthread_create(&ioThread, NULL, ioThreadEntry, this) != 0) {
		perror("Could not create audio thread");
	}
	running = true;
}

/*! RPU::~RPU()
 * @author James Johns
 * @brief RPU destructor
 *
 */
RPU::~RPU()
{
	running = false;
	player->stop();
	pthread_join(ioThread, NULL);
	pthread_join(audioThread, NULL);
	delete player;
	delete input;
	delete display;
	delete cddapi;
}

/*! RPU::tick()
 * @author James Johns
 * @brief RPU update tick
 *
 * Call iteratively to allow RPU to execute next action.
 * Handles events sent to the RPU, such as input, stream requests etc.
 */
void RPU::tick()
{
	//Checks for incoming broadcast. Mutes regular streaming
	//Returns bool; true if broadcasting, false if not
	player->listen();

	Event *evt = getEvent();
	do {
		if (evt != NULL) {
			if (evt->getType() == Event::QUIT) {
				running = false;
			}
		}
		switch (state) {
		case LOGIN_PROMPT:
			loginPrompt(evt);
			break;
		case DISPLAY_MENU:
			displayMenu(evt);
			break;
		case SELECT_LANGUAGE:
			selectLanguage(evt);
			break;
		case SELECT_KNOWLEDGE:
			selectKnowledge(evt);
			break;
		default:
			break;
		}

		if (evt != NULL)
			delete evt;
		evt = getEvent();
	} while (evt != NULL);
}

/*! RPU::sendEvent(Event *evt)
 * @author James Johns
 * @brief Send Event to RPU
 *
 * @param[in] evt Event to place in event queue
 */
void RPU::sendEvent(Event *evt)
{
	eventQueue->push(evt);
}

/*! RPU::getEvent()
 * @author James Johns
 * @brief Get event in event queue
 *
 * @return Event at front of event queue. Returns NULL if queue is empty.
 */
Event *RPU::getEvent()
{
	Event *evt = NULL;
	if (!eventQueue->empty()) {
		evt = eventQueue->front();
		eventQueue->pop();
	}
	return evt;
}

/*! RPU::getIPAddress()
 * @author James Johns
 * @brief Find the device's current IP address
 *
 * @return List of strings containing IP addresses that the device is associated with
 */
std::vector<char *> *RPU::getIPAddress()
{
	struct ifaddrs *ifAddrs = NULL, *curAddr = NULL;
	void *tmpAddr = NULL;
	char *tmpStr = NULL;
	std::vector<char *> *toRet = new std::vector<char *>;

	getifaddrs(&ifAddrs);

	for (curAddr = ifAddrs; curAddr != NULL; curAddr = curAddr->ifa_next) {
		if (!curAddr->ifa_addr)
			continue;

		if (curAddr->ifa_addr->sa_family == AF_INET) {
			tmpAddr = &((struct sockaddr_in *)curAddr->ifa_addr)->sin_addr;
			tmpStr = new char[INET_ADDRSTRLEN];
			inet_ntop(AF_INET, tmpAddr, tmpStr, INET_ADDRSTRLEN);
			toRet->push_back(tmpStr);

		} else {
			continue;
		}
	}

	return toRet;
}

void RPU::loginPrompt(Event *evt)
{
	static bool entered = false;

	if (entered == false) {
		display->setErrorString("Please enter PIN to unlock");
		entered = true;
	}

	if (evt == NULL)
		return;

	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'q':
			running = false;
			break;
		case 'c':/*!< Enter key */
			/* enter selected menu entry */
			if (cddapi->login(numberInput.c_str()) == 0) {
				state = DISPLAY_MENU;
				display->setMenuString(mainMenu->getCurrentMenuItem());
				display->setErrorString(NULL);
				entered = false;
			} else {
				display->setErrorString(cddapi->getLastSentMessage().c_str());
			}
			break;
		case '1' ... '9':
			/* capture PIN input */
			numberInput.push_back(*(char *)evt->getArguments());
			if (numberInput.length() > 4) // pop data from front of string to reduce to 4 character string
				numberInput.erase(0, numberInput.length() - 4);
			break;
		case 'p':/*!< play */
		case 'r':/*!< rewind */
		case 'f':/*!< Fast Forward */
		case 'w':/*!< Up key */
		case 's':/*!< Down key */
		default:
			/* ignored */
			break;
		}
		break;
	default:
		break;
	}
}

void RPU::displayMenu(Event *evt)
{
	static bool entered = false;

	if (entered == false) {
		display->setMenuString(mainMenu->getCurrentMenuItem());
		entered = true;
	}

	if (evt == NULL)
		return;

	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'p':
			if (player != NULL) {
				player->playpause();
				display->setPlaybackString(((player->isPlaying()) ? "Play" : "Pause"));
			}
			break;
		case 'r':
		  if (player != NULL) {
				player->rewind();
			}
			break;
		case 'f': /*!< Fast Forward */
		  if (player != NULL) {
		    player->fastForward();
		  }
			break;
		case 'q':
			state = LOGIN_PROMPT;
			display->setErrorString("Please enter PIN to unlock");
			display->setMenuString(NULL);
			display->setPlaybackString(NULL);
			display->setTrackInfoString(NULL);
			break;
		case 'w':/*!< Up key */
			mainMenu->up();
			display->setMenuString(mainMenu->getCurrentMenuItem());
			break;
		case 's':/*!< Down key */
			mainMenu->down();
			display->setMenuString(mainMenu->getCurrentMenuItem());
			break;
		case 'c':/*!< Enter (continue) key */
			/* Enter selected menu entry */
			if (mainMenu->getCurrentSelected() == 0) {
				display->setErrorString(numberInput.c_str());
				cddapi->requestAudioStream(numberInput.c_str());
				player->play();
			} else if (mainMenu->getCurrentSelected() == 1) {
				state = SELECT_LANGUAGE;
				entered = false;
			} else if (mainMenu->getCurrentSelected() == 2) {
				state = SELECT_KNOWLEDGE;
				entered = false;
			}
			break;
		case '1' ... '9':
			numberInput.push_back(*(char *)evt->getArguments());
			if (numberInput.length() > 4) // pop data from front of string to reduce to 4 character string
				numberInput.erase(0, numberInput.length() - 4);
			break;
		default:
			break;
		}
		break;
	default:
		break;
	}
}

void RPU::selectLanguage(Event *evt)
{
	static bool entered = false;
	static int language = 0;
	char *langString;
	int tmpLang = language;
	std::vector<std::string> supportedLanguages = cddapi->getSupportedLanguages();

	if (entered == false) {
		do {
			language++;
			langString = (char *) supportedLanguages[language].c_str();
		} while (langString == NULL && language < supportedLanguages.size());
		if (language >= supportedLanguages.size())
			language = tmpLang;
		display->setMenuString(supportedLanguages[language].c_str());
		entered = true;
	}

	if (evt == NULL)
		return;

	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'p':
			if (player != NULL) {
				player->playpause();
				display->setPlaybackString((char *)((player->isPlaying()) ? "Play" : "Pause"));
			}
			break;
		case 'r':
			if (player != NULL) {
				player->rewind();
			}
			break;
		case 'f': /*!< Fast Forward */
		  if (player != NULL) {
		    player->fastForward();
		  }
			break;
		case 'q':
			state = DISPLAY_MENU;
			entered = false;
			break;
		case 'w':/*!< Up key */
			do {
				language++;
				langString = (char *) supportedLanguages[language].c_str();
			} while (langString == NULL && language < supportedLanguages.size());
			if (language >= supportedLanguages.size())
				language = tmpLang;
			display->setMenuString(supportedLanguages[language].c_str());
			break;
		case 's':/*!< Down key */
			do {
				language--;
				langString = (char *) supportedLanguages[language].c_str();
			} while (langString == NULL && language > 0);
			if (language < 0)
				language = tmpLang;
			display->setMenuString(supportedLanguages[language].c_str());
			break;
		case 'c':/*!< Enter key */
			cddapi->changeLanguage(language);
			state = DISPLAY_MENU;
			entered = false;
			break;
		case '1' ... '9':
		default:
			break;
		}
		break;
	default:
		break;
	}
}

void RPU::selectKnowledge(Event *evt)
{
	static bool entered = false;
	static int knowledge = 0;
	char *knowString;
	int tmpKnow = knowledge;
	std::vector<std::string> supportedKnowledgeLevels = cddapi->getSupportedKnowledgeLevels();

	if (entered == false) {
		do {
			knowledge++;
			knowString = (char *) supportedKnowledgeLevels[knowledge].c_str();
		} while (knowString == NULL && knowledge < supportedKnowledgeLevels.size());
		if (knowledge >= supportedKnowledgeLevels.size())
			knowledge = tmpKnow;
		display->setMenuString(supportedKnowledgeLevels[knowledge].c_str());
		entered = true;
	}

	if (evt == NULL)
		return;

	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'p':
			if (player != NULL) {
				player->playpause();
				display->setPlaybackString((char *)((player->isPlaying()) ? "Play" : "Pause"));
			}
			break;
		case 'r':
			if (player != NULL) {
				player->rewind();
			}
			break;
		case 'f':/*!< Fast Forward */
		  if(player != NULL) {
		    player->fastForward();
		  }
			break;
		case 'q':
			state = DISPLAY_MENU;
			entered = false;
			break;
		case 'c':/*!< Enter key */
			cddapi->changeKnowledgeLevel(knowledge);
			state = DISPLAY_MENU;
			entered = false;
			break;
		case 'w':/*!< Up key */
			do {
				knowledge++;
				knowString = (char *) supportedKnowledgeLevels[knowledge].c_str();
			} while (knowString == NULL && knowledge < supportedKnowledgeLevels.size());
			if (knowledge >= supportedKnowledgeLevels.size())
				knowledge = tmpKnow;
			display->setMenuString(supportedKnowledgeLevels[knowledge].c_str());
			break;
		case 's':/*!< Down key */
			do {
				knowledge--;
				knowString = (char *) supportedKnowledgeLevels[knowledge].c_str();
			} while (knowString == NULL && knowledge >= 0);
			if (knowledge < 0)
				knowledge = tmpKnow;
			display->setMenuString(supportedKnowledgeLevels[knowledge].c_str());
			break;
		case '1' ... '9':
		default:
			break;
		}
		break;
	default:
		break;
	}
}

void RPU::requestStream(Event *evt)
{
	switch (evt->getType()) {
	case Event::KEYPAD_INPUT:
		switch (*(char *)evt->getArguments()) {
		case 'p':
			if (player != NULL) {
				player->playpause();
				display->setPlaybackString((char *)((player->isPlaying()) ? "Play" : "Pause"));
			}
			break;
		case 'r':
			if (player != NULL) {
				player->rewind();
			}
			break;
		case 'f':/*!< Fast Forward */
		  if (player != NULL) {
		    player->fastForward();
		  }
			break;
		case 'q': /* cancel key - return to menu */
			state = DISPLAY_MENU;
			break;
		case 'c':/*!< Enter key */
			/* TODO: Request stream using last 4 digits input */
			break;
		case '1' ... '9':
			/* TODO: Capture Exhibit ID input */
			break;
		case 'w':/*!< Up key */
		case 's':/*!< Down key */
		default:
			// Unused
			break;
		}
		break;
	default:
		break;
	}
}
<|endoftext|>


<commit_before>/**************************************************************************
 *
 * Copyright 2011 Jose Fonseca
 * All Rights Reserved.
 *
 * 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.
 *
 **************************************************************************/

/*
 * Simple OS time measurement abstraction.
 */

#ifndef _OS_TIME_HPP_
#define _OS_TIME_HPP_

#if defined(_WIN32)
#  include <windows.h>
#else
#  if defined(__linux__)
#    include <time.h>
#  elif defined(__APPLE__)
#    include <mach/mach_time.h>
#  else
#    include <sys/time.h>
#  endif
#  include <unistd.h>
#endif

namespace os {

    // OS dependent time frequency
#if defined(_WIN32) || defined(__APPLE__)
    // runtime variable on Windows and MacOSX
    extern long long timeFrequency;
#elif defined(__linux__)
    // nanoseconds on Linux
    static const long long timeFrequency = 1000000000LL;
#else
    // microseconds on Unices
    static const long long timeFrequency = 1000000LL;
#endif

    // Time from an unknown base in a unit determined by timeFrequency
    inline long long
    getTime(void) {
#if defined(_WIN32)
        if (!timeFrequency) {
            LARGE_INTEGER frequency;
            QueryPerformanceFrequency(&frequency);
            timeFrequency = frequency.QuadPart;
        }
        LARGE_INTEGER counter;
        QueryPerformanceCounter(&counter);
        return counter.QuadPart;
#elif defined(__linux__)
        struct timespec tp;
        if (clock_gettime(CLOCK_REALTIME, &tp) == -1) {
            return 0;
        }
        return tp.tv_sec * 1000000000LL + tp.tv_nsec;
#elif defined(__APPLE__)
        if (!timeFrequency) {
            mach_timebase_info_data_t timebaseInfo;
            mach_timebase_info(&timebaseInfo);
            timeFrequency = 1000000000LL * timebaseInfo.denom / timebaseInfo.numer;
        }
        return mach_absolute_time();
#else
        struct timeval tv;
        gettimeofday(&tv, NULL);
        return tv.tv_sec * 1000000LL + tv.tv_usec;
#endif
    }

    // Suspend execution
    inline void
    sleep(unsigned long usecs) {
#if defined(_WIN32)
        Sleep((usecs + 999) / 1000);
#else
        usleep(usecs);
#endif
    }

} /* namespace os */

#endif /* _OS_TIME_HPP_ */
<commit_msg>os: Use CLOCK_MONOTONIC<commit_after>/**************************************************************************
 *
 * Copyright 2011 Jose Fonseca
 * All Rights Reserved.
 *
 * 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.
 *
 **************************************************************************/

/*
 * Simple OS time measurement abstraction.
 */

#ifndef _OS_TIME_HPP_
#define _OS_TIME_HPP_

#if defined(_WIN32)
#  include <windows.h>
#else
#  if defined(__linux__)
#    include <time.h>
#  elif defined(__APPLE__)
#    include <mach/mach_time.h>
#  else
#    include <sys/time.h>
#  endif
#  include <unistd.h>
#endif

namespace os {

    // OS dependent time frequency
#if defined(_WIN32) || defined(__APPLE__)
    // runtime variable on Windows and MacOSX
    extern long long timeFrequency;
#elif defined(__linux__)
    // nanoseconds on Linux
    static const long long timeFrequency = 1000000000LL;
#else
    // microseconds on Unices
    static const long long timeFrequency = 1000000LL;
#endif

    // Time from an unknown base in a unit determined by timeFrequency
    inline long long
    getTime(void) {
#if defined(_WIN32)
        if (!timeFrequency) {
            LARGE_INTEGER frequency;
            QueryPerformanceFrequency(&frequency);
            timeFrequency = frequency.QuadPart;
        }
        LARGE_INTEGER counter;
        QueryPerformanceCounter(&counter);
        return counter.QuadPart;
#elif defined(__linux__)
        struct timespec tp;
        if (clock_gettime(CLOCK_MONOTONIC, &tp) == -1) {
            return 0;
        }
        return tp.tv_sec * 1000000000LL + tp.tv_nsec;
#elif defined(__APPLE__)
        if (!timeFrequency) {
            mach_timebase_info_data_t timebaseInfo;
            mach_timebase_info(&timebaseInfo);
            timeFrequency = 1000000000LL * timebaseInfo.denom / timebaseInfo.numer;
        }
        return mach_absolute_time();
#else
        struct timeval tv;
        gettimeofday(&tv, NULL);
        return tv.tv_sec * 1000000LL + tv.tv_usec;
#endif
    }

    // Suspend execution
    inline void
    sleep(unsigned long usecs) {
#if defined(_WIN32)
        Sleep((usecs + 999) / 1000);
#else
        usleep(usecs);
#endif
    }

} /* namespace os */

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


<commit_before>// @(#)root/hist:$Id$
// Author: Rene Brun   12/12/94

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "TROOT.h"
#include "TVirtualPad.h"
#include "TPolyMarker.h"
#include "TClass.h"
#include "TMath.h"

ClassImp(TPolyMarker)

//______________________________________________________________________________
//
//  a PolyMarker is defined by an array on N points in a 2-D space.
// At each point x[i], y[i] a marker is drawn.
// Marker attributes are managed by TAttMarker.
// See TMarker for the list of possible marker types.
//

//______________________________________________________________________________
TPolyMarker::TPolyMarker(): TObject()
{
   // Default constructor.

   fN = 0;
   fX = fY = 0;
   fLastPoint = -1;
}

//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Option_t *option)
      :TObject(), TAttMarker()
{
   // Constructor.

   fOption = option;
   SetBit(kCanDelete);
   fLastPoint = -1;
   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      fX = fY = 0;
      return;
   }
   fN = n;
   fX = new Double_t [fN];
   fY = new Double_t [fN];
}

//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)
      :TObject(), TAttMarker()
{
   // Constructor.

   fOption = option;
   SetBit(kCanDelete);
   fLastPoint = -1;
   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      fX = fY = 0;
      return;
   }
   fN = n;
   fX = new Double_t [fN];
   fY = new Double_t [fN];
   if (!x || !y) return;
   for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }
   fLastPoint = fN-1;
}

//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
      :TObject(), TAttMarker()
{
   // Constructor.

   fOption = option;
   SetBit(kCanDelete);
   fLastPoint = -1;
   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      fX = fY = 0;
      return;
   }
   fN = n;
   fX = new Double_t [fN];
   fY = new Double_t [fN];
   if (!x || !y) return;
   for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }
   fLastPoint = fN-1;
}

//______________________________________________________________________________
TPolyMarker& TPolyMarker::operator=(const TPolyMarker& pm)
{
   //assignment operator
   if(this!=&pm) {
      TObject::operator=(pm);
      TAttMarker::operator=(pm);
      fN=pm.fN;
      fLastPoint=pm.fLastPoint;
      fX=pm.fX;
      fY=pm.fY;
      fOption=pm.fOption;
   }
   return *this;
}

//______________________________________________________________________________
TPolyMarker::~TPolyMarker()
{
   // Desctructor.

   if (fX) delete [] fX;
   if (fY) delete [] fY;
   fLastPoint = -1;
}

//______________________________________________________________________________
TPolyMarker::TPolyMarker(const TPolyMarker &polymarker) : TObject(polymarker), TAttMarker(polymarker)
{
   // Copy constructor.

   fN = 0;
   fLastPoint = -1;
   ((TPolyMarker&)polymarker).Copy(*this);
}

//______________________________________________________________________________
void TPolyMarker::Copy(TObject &obj) const
{

   // Copy.

   TObject::Copy(obj);
   TAttMarker::Copy(((TPolyMarker&)obj));
   ((TPolyMarker&)obj).fN = fN;
   if (fN > 0) {
      ((TPolyMarker&)obj).fX = new Double_t [fN];
      ((TPolyMarker&)obj).fY = new Double_t [fN];
      for (Int_t i=0; i<fN;i++) { ((TPolyMarker&)obj).fX[i] = fX[i], ((TPolyMarker&)obj).fY[i] = fY[i]; }
   } else {
      ((TPolyMarker&)obj).fX = 0;
      ((TPolyMarker&)obj).fY = 0;
   }
   ((TPolyMarker&)obj).fOption = fOption;
   ((TPolyMarker&)obj).fLastPoint = fLastPoint;
}

//______________________________________________________________________________
Int_t TPolyMarker::DistancetoPrimitive(Int_t px, Int_t py)
{
   // Compute distance from point px,py to a polymarker.
   //
   //  Compute the closest distance of approach from point px,py to each point
   //  of the polymarker.
   //  Returns when the distance found is below DistanceMaximum.
   //  The distance is computed in pixels units.

   const Int_t big = 9999;

   // check if point is near one of the points
   Int_t i, pxp, pyp, d;
   Int_t distance = big;

   for (i=0;i<Size();i++) {
      pxp = gPad->XtoAbsPixel(gPad->XtoPad(fX[i]));
      pyp = gPad->YtoAbsPixel(gPad->YtoPad(fY[i]));
      d   = TMath::Abs(pxp-px) + TMath::Abs(pyp-py);
      if (d < distance) distance = d;
   }
   return distance;
}

//______________________________________________________________________________
void TPolyMarker::Draw(Option_t *option)
{
   // Draw.

   AppendPad(option);
}

//______________________________________________________________________________
void TPolyMarker::DrawPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *)
{
   // Draw polymarker.

   TPolyMarker *newpolymarker = new TPolyMarker(n,x,y);
   TAttMarker::Copy(*newpolymarker);
   newpolymarker->fOption = fOption;
   newpolymarker->SetBit(kCanDelete);
   newpolymarker->AppendPad();
}

//______________________________________________________________________________
void TPolyMarker::ExecuteEvent(Int_t, Int_t, Int_t)
{
   // Execute action corresponding to one event.
   //
   //  This member function must be implemented to realize the action
   //  corresponding to the mouse click on the object in the window
}

//______________________________________________________________________________
void TPolyMarker::ls(Option_t *) const
{
   // ls.

   TROOT::IndentLevel();
   printf("TPolyMarker  N=%d\n",fN);
}

//______________________________________________________________________________
Int_t TPolyMarker::Merge(TCollection *li)
{
   // Merge polymarkers in the collection in this polymarker.

   if (!li) return 0;
   TIter next(li);

   //first loop to count the number of entries
   TPolyMarker *pm;
   Int_t npoints = 0;
   while ((pm = (TPolyMarker*)next())) {
      if (!pm->InheritsFrom(TPolyMarker::Class())) {
         Error("Add","Attempt to add object of class: %s to a %s",pm->ClassName(),this->ClassName());
         return -1;
      }
      npoints += pm->Size();
   }

   //extend this polymarker to hold npoints
   SetPoint(npoints-1,0,0);

   //merge all polymarkers
   next.Reset();
   while ((pm = (TPolyMarker*)next())) {
      Int_t np = pm->Size();
      Double_t *x = pm->GetX();
      Double_t *y = pm->GetY();
      for (Int_t i=0;i<np;i++) {
         SetPoint(i,x[i],y[i]);
      }
   }

   return npoints;
}

//______________________________________________________________________________
void TPolyMarker::Paint(Option_t *option)
{
   // Paint.

   PaintPolyMarker(fLastPoint+1, fX, fY, option);
}

//______________________________________________________________________________
void TPolyMarker::PaintPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
{
   // Paint polymarker.

   if (n <= 0) return;
   TAttMarker::Modify();  //Change marker attributes only if necessary
   Double_t *xx = x;
   Double_t *yy = y;
   if (gPad->GetLogx()) {
      xx = new Double_t[n];
      for (Int_t ix=0;ix<n;ix++) xx[ix] = gPad->XtoPad(x[ix]);
   }
   if (gPad->GetLogy()) {
      yy = new Double_t[n];
      for (Int_t iy=0;iy<n;iy++) yy[iy] = gPad->YtoPad(y[iy]);
   }
   gPad->PaintPolyMarker(n,xx,yy,option);
   if (x != xx) delete [] xx;
   if (y != yy) delete [] yy;
}

//______________________________________________________________________________
void TPolyMarker::Print(Option_t *) const
{
   // Print polymarker.

   printf("TPolyMarker  N=%d\n",fN);
}

//______________________________________________________________________________
void TPolyMarker::SavePrimitive(ostream &out, Option_t *option /*= ""*/)
{
   // Save primitive as a C++ statement(s) on output stream out.

   char quote = '"';
   out<<"   "<<endl;
   out<<"   Double_t *dum = 0;"<<endl;
   if (gROOT->ClassSaved(TPolyMarker::Class())) {
      out<<"   ";
   } else {
      out<<"   TPolyMarker *";
   }
   out<<"pmarker = new TPolyMarker("<<fN<<",dum,dum,"<<quote<<fOption<<quote<<");"<<endl;

   SaveMarkerAttributes(out,"pmarker",1,1,1);

   for (Int_t i=0;i<Size();i++) {
      out<<"   pmarker->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl;
   }
   out<<"   pmarker->Draw("
      <<quote<<option<<quote<<");"<<endl;
}

//______________________________________________________________________________
Int_t TPolyMarker::SetNextPoint(Double_t x, Double_t y)
{
   // Set point following LastPoint to x, y.
   // Returns index of the point (new last point).

   fLastPoint++;
   SetPoint(fLastPoint, x, y);
   return fLastPoint;
}

//______________________________________________________________________________
void TPolyMarker::SetPoint(Int_t n, Double_t x, Double_t y)
{
   // Set point number n.
   // if n is greater than the current size, the arrays are automatically
   // extended

   if (n < 0) return;
   if (!fX || !fY || n >= fN) {
      // re-allocate the object
      Int_t newN = TMath::Max(2*fN,n+1);
      Double_t *savex = new Double_t [newN];
      Double_t *savey = new Double_t [newN];
      if (fX && fN){
         memcpy(savex,fX,fN*sizeof(Double_t));
         memset(&savex[fN],0,(newN-fN)*sizeof(Double_t));
         delete [] fX;
      }
      if (fY && fN){
         memcpy(savey,fY,fN*sizeof(Double_t));
         memset(&savey[fN],0,(newN-fN)*sizeof(Double_t));
         delete [] fY;
      }
      fX = savex;
      fY = savey;
      fN = newN;
   }
   fX[n] = x;
   fY[n] = y;
   fLastPoint = TMath::Max(fLastPoint,n);
}

//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n)
{
   // If n <= 0 the current arrays of points are deleted.

   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      delete [] fX;
      delete [] fY;
      fX = fY = 0;
      return;
   }
   SetPoint(n-1,0,0);
}

//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)
{
   // If n <= 0 the current arrays of points are deleted.

   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      delete [] fX;
      delete [] fY;
      fX = fY = 0;
      return;
   }
   fN =n;
   if (fX) delete [] fX;
   if (fY) delete [] fY;
   fX = new Double_t[fN];
   fY = new Double_t[fN];
   for (Int_t i=0; i<fN;i++) {
      if (x) fX[i] = (Double_t)x[i];
      if (y) fY[i] = (Double_t)y[i];
   }
   fOption = option;
   fLastPoint = fN-1;
}

//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
{
   // If n <= 0 the current arrays of points are deleted.

   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      delete [] fX;
      delete [] fY;
      fX = fY = 0;
      return;
   }
   fN =n;
   if (fX) delete [] fX;
   if (fY) delete [] fY;
   fX = new Double_t[fN];
   fY = new Double_t[fN];
   for (Int_t i=0; i<fN;i++) {
      if (x) fX[i] = x[i];
      if (y) fY[i] = y[i];
   }
   fOption = option;
   fLastPoint = fN-1;
}

//_______________________________________________________________________
void TPolyMarker::Streamer(TBuffer &R__b)
{
   // Stream a class object.

   if (R__b.IsReading()) {
      UInt_t R__s, R__c;
      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
      if (R__v > 1) {
         R__b.ReadClassBuffer(TPolyMarker::Class(), this, R__v, R__s, R__c);
         return;
      }
      //====process old versions before automatic schema evolution
      TObject::Streamer(R__b);
      TAttMarker::Streamer(R__b);
      R__b >> fN;
      fX = new Double_t[fN];
      fY = new Double_t[fN];
      Int_t i;
      Float_t xold,yold;
      for (i=0;i<fN;i++) {R__b >> xold; fX[i] = xold;}
      for (i=0;i<fN;i++) {R__b >> yold; fY[i] = yold;}
      fOption.Streamer(R__b);
      R__b.CheckByteCount(R__s, R__c, TPolyMarker::IsA());
      //====end of old versions

   } else {
      R__b.WriteClassBuffer(TPolyMarker::Class(),this);
   }
}
<commit_msg>- Fix coverity report #11208: UNINIT_CTOR<commit_after>// @(#)root/hist:$Id$
// Author: Rene Brun   12/12/94

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "TROOT.h"
#include "TVirtualPad.h"
#include "TPolyMarker.h"
#include "TClass.h"
#include "TMath.h"

ClassImp(TPolyMarker)

//______________________________________________________________________________
//
//  a PolyMarker is defined by an array on N points in a 2-D space.
// At each point x[i], y[i] a marker is drawn.
// Marker attributes are managed by TAttMarker.
// See TMarker for the list of possible marker types.
//

//______________________________________________________________________________
TPolyMarker::TPolyMarker(): TObject()
{
   // Default constructor.

   fN = 0;
   fX = fY = 0;
   fLastPoint = -1;
}

//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Option_t *option)
      :TObject(), TAttMarker()
{
   // Constructor.

   fOption = option;
   SetBit(kCanDelete);
   fLastPoint = -1;
   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      fX = fY = 0;
      return;
   }
   fN = n;
   fX = new Double_t [fN];
   fY = new Double_t [fN];
}

//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)
      :TObject(), TAttMarker()
{
   // Constructor.

   fOption = option;
   SetBit(kCanDelete);
   fLastPoint = -1;
   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      fX = fY = 0;
      return;
   }
   fN = n;
   fX = new Double_t [fN];
   fY = new Double_t [fN];
   if (!x || !y) return;
   for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }
   fLastPoint = fN-1;
}

//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
      :TObject(), TAttMarker()
{
   // Constructor.

   fOption = option;
   SetBit(kCanDelete);
   fLastPoint = -1;
   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      fX = fY = 0;
      return;
   }
   fN = n;
   fX = new Double_t [fN];
   fY = new Double_t [fN];
   if (!x || !y) return;
   for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }
   fLastPoint = fN-1;
}

//______________________________________________________________________________
TPolyMarker& TPolyMarker::operator=(const TPolyMarker& pm)
{
   //assignment operator
   if(this!=&pm) {
      TObject::operator=(pm);
      TAttMarker::operator=(pm);
      fN=pm.fN;
      fLastPoint=pm.fLastPoint;
      fX=pm.fX;
      fY=pm.fY;
      fOption=pm.fOption;
   }
   return *this;
}

//______________________________________________________________________________
TPolyMarker::~TPolyMarker()
{
   // Desctructor.

   if (fX) delete [] fX;
   if (fY) delete [] fY;
   fLastPoint = -1;
}

//______________________________________________________________________________
TPolyMarker::TPolyMarker(const TPolyMarker &polymarker) : TObject(polymarker), TAttMarker(polymarker)
{
   // Copy constructor.

   fN = 0;
   fX = fY = 0;
   fLastPoint = -1;
   ((TPolyMarker&)polymarker).Copy(*this);
}

//______________________________________________________________________________
void TPolyMarker::Copy(TObject &obj) const
{

   // Copy.

   TObject::Copy(obj);
   TAttMarker::Copy(((TPolyMarker&)obj));
   ((TPolyMarker&)obj).fN = fN;
   if (fN > 0) {
      ((TPolyMarker&)obj).fX = new Double_t [fN];
      ((TPolyMarker&)obj).fY = new Double_t [fN];
      for (Int_t i=0; i<fN;i++) { ((TPolyMarker&)obj).fX[i] = fX[i], ((TPolyMarker&)obj).fY[i] = fY[i]; }
   } else {
      ((TPolyMarker&)obj).fX = 0;
      ((TPolyMarker&)obj).fY = 0;
   }
   ((TPolyMarker&)obj).fOption = fOption;
   ((TPolyMarker&)obj).fLastPoint = fLastPoint;
}

//______________________________________________________________________________
Int_t TPolyMarker::DistancetoPrimitive(Int_t px, Int_t py)
{
   // Compute distance from point px,py to a polymarker.
   //
   //  Compute the closest distance of approach from point px,py to each point
   //  of the polymarker.
   //  Returns when the distance found is below DistanceMaximum.
   //  The distance is computed in pixels units.

   const Int_t big = 9999;

   // check if point is near one of the points
   Int_t i, pxp, pyp, d;
   Int_t distance = big;

   for (i=0;i<Size();i++) {
      pxp = gPad->XtoAbsPixel(gPad->XtoPad(fX[i]));
      pyp = gPad->YtoAbsPixel(gPad->YtoPad(fY[i]));
      d   = TMath::Abs(pxp-px) + TMath::Abs(pyp-py);
      if (d < distance) distance = d;
   }
   return distance;
}

//______________________________________________________________________________
void TPolyMarker::Draw(Option_t *option)
{
   // Draw.

   AppendPad(option);
}

//______________________________________________________________________________
void TPolyMarker::DrawPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *)
{
   // Draw polymarker.

   TPolyMarker *newpolymarker = new TPolyMarker(n,x,y);
   TAttMarker::Copy(*newpolymarker);
   newpolymarker->fOption = fOption;
   newpolymarker->SetBit(kCanDelete);
   newpolymarker->AppendPad();
}

//______________________________________________________________________________
void TPolyMarker::ExecuteEvent(Int_t, Int_t, Int_t)
{
   // Execute action corresponding to one event.
   //
   //  This member function must be implemented to realize the action
   //  corresponding to the mouse click on the object in the window
}

//______________________________________________________________________________
void TPolyMarker::ls(Option_t *) const
{
   // ls.

   TROOT::IndentLevel();
   printf("TPolyMarker  N=%d\n",fN);
}

//______________________________________________________________________________
Int_t TPolyMarker::Merge(TCollection *li)
{
   // Merge polymarkers in the collection in this polymarker.

   if (!li) return 0;
   TIter next(li);

   //first loop to count the number of entries
   TPolyMarker *pm;
   Int_t npoints = 0;
   while ((pm = (TPolyMarker*)next())) {
      if (!pm->InheritsFrom(TPolyMarker::Class())) {
         Error("Add","Attempt to add object of class: %s to a %s",pm->ClassName(),this->ClassName());
         return -1;
      }
      npoints += pm->Size();
   }

   //extend this polymarker to hold npoints
   SetPoint(npoints-1,0,0);

   //merge all polymarkers
   next.Reset();
   while ((pm = (TPolyMarker*)next())) {
      Int_t np = pm->Size();
      Double_t *x = pm->GetX();
      Double_t *y = pm->GetY();
      for (Int_t i=0;i<np;i++) {
         SetPoint(i,x[i],y[i]);
      }
   }

   return npoints;
}

//______________________________________________________________________________
void TPolyMarker::Paint(Option_t *option)
{
   // Paint.

   PaintPolyMarker(fLastPoint+1, fX, fY, option);
}

//______________________________________________________________________________
void TPolyMarker::PaintPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
{
   // Paint polymarker.

   if (n <= 0) return;
   TAttMarker::Modify();  //Change marker attributes only if necessary
   Double_t *xx = x;
   Double_t *yy = y;
   if (gPad->GetLogx()) {
      xx = new Double_t[n];
      for (Int_t ix=0;ix<n;ix++) xx[ix] = gPad->XtoPad(x[ix]);
   }
   if (gPad->GetLogy()) {
      yy = new Double_t[n];
      for (Int_t iy=0;iy<n;iy++) yy[iy] = gPad->YtoPad(y[iy]);
   }
   gPad->PaintPolyMarker(n,xx,yy,option);
   if (x != xx) delete [] xx;
   if (y != yy) delete [] yy;
}

//______________________________________________________________________________
void TPolyMarker::Print(Option_t *) const
{
   // Print polymarker.

   printf("TPolyMarker  N=%d\n",fN);
}

//______________________________________________________________________________
void TPolyMarker::SavePrimitive(ostream &out, Option_t *option /*= ""*/)
{
   // Save primitive as a C++ statement(s) on output stream out.

   char quote = '"';
   out<<"   "<<endl;
   out<<"   Double_t *dum = 0;"<<endl;
   if (gROOT->ClassSaved(TPolyMarker::Class())) {
      out<<"   ";
   } else {
      out<<"   TPolyMarker *";
   }
   out<<"pmarker = new TPolyMarker("<<fN<<",dum,dum,"<<quote<<fOption<<quote<<");"<<endl;

   SaveMarkerAttributes(out,"pmarker",1,1,1);

   for (Int_t i=0;i<Size();i++) {
      out<<"   pmarker->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl;
   }
   out<<"   pmarker->Draw("
      <<quote<<option<<quote<<");"<<endl;
}

//______________________________________________________________________________
Int_t TPolyMarker::SetNextPoint(Double_t x, Double_t y)
{
   // Set point following LastPoint to x, y.
   // Returns index of the point (new last point).

   fLastPoint++;
   SetPoint(fLastPoint, x, y);
   return fLastPoint;
}

//______________________________________________________________________________
void TPolyMarker::SetPoint(Int_t n, Double_t x, Double_t y)
{
   // Set point number n.
   // if n is greater than the current size, the arrays are automatically
   // extended

   if (n < 0) return;
   if (!fX || !fY || n >= fN) {
      // re-allocate the object
      Int_t newN = TMath::Max(2*fN,n+1);
      Double_t *savex = new Double_t [newN];
      Double_t *savey = new Double_t [newN];
      if (fX && fN){
         memcpy(savex,fX,fN*sizeof(Double_t));
         memset(&savex[fN],0,(newN-fN)*sizeof(Double_t));
         delete [] fX;
      }
      if (fY && fN){
         memcpy(savey,fY,fN*sizeof(Double_t));
         memset(&savey[fN],0,(newN-fN)*sizeof(Double_t));
         delete [] fY;
      }
      fX = savex;
      fY = savey;
      fN = newN;
   }
   fX[n] = x;
   fY[n] = y;
   fLastPoint = TMath::Max(fLastPoint,n);
}

//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n)
{
   // If n <= 0 the current arrays of points are deleted.

   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      delete [] fX;
      delete [] fY;
      fX = fY = 0;
      return;
   }
   SetPoint(n-1,0,0);
}

//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)
{
   // If n <= 0 the current arrays of points are deleted.

   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      delete [] fX;
      delete [] fY;
      fX = fY = 0;
      return;
   }
   fN =n;
   if (fX) delete [] fX;
   if (fY) delete [] fY;
   fX = new Double_t[fN];
   fY = new Double_t[fN];
   for (Int_t i=0; i<fN;i++) {
      if (x) fX[i] = (Double_t)x[i];
      if (y) fY[i] = (Double_t)y[i];
   }
   fOption = option;
   fLastPoint = fN-1;
}

//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
{
   // If n <= 0 the current arrays of points are deleted.

   if (n <= 0) {
      fN = 0;
      fLastPoint = -1;
      delete [] fX;
      delete [] fY;
      fX = fY = 0;
      return;
   }
   fN =n;
   if (fX) delete [] fX;
   if (fY) delete [] fY;
   fX = new Double_t[fN];
   fY = new Double_t[fN];
   for (Int_t i=0; i<fN;i++) {
      if (x) fX[i] = x[i];
      if (y) fY[i] = y[i];
   }
   fOption = option;
   fLastPoint = fN-1;
}

//_______________________________________________________________________
void TPolyMarker::Streamer(TBuffer &R__b)
{
   // Stream a class object.

   if (R__b.IsReading()) {
      UInt_t R__s, R__c;
      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
      if (R__v > 1) {
         R__b.ReadClassBuffer(TPolyMarker::Class(), this, R__v, R__s, R__c);
         return;
      }
      //====process old versions before automatic schema evolution
      TObject::Streamer(R__b);
      TAttMarker::Streamer(R__b);
      R__b >> fN;
      fX = new Double_t[fN];
      fY = new Double_t[fN];
      Int_t i;
      Float_t xold,yold;
      for (i=0;i<fN;i++) {R__b >> xold; fX[i] = xold;}
      for (i=0;i<fN;i++) {R__b >> yold; fY[i] = yold;}
      fOption.Streamer(R__b);
      R__b.CheckByteCount(R__s, R__c, TPolyMarker::IsA());
      //====end of old versions

   } else {
      R__b.WriteClassBuffer(TPolyMarker::Class(),this);
   }
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX グループ・QSPI I/O 制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/vect.h"

/// F_PCKx は速度パラメーター計算で必要で、設定が無いとエラーにします。
#if defined(SIG_RX24T)
#  error "qspi_io.hpp not support for RX24T"
#elif defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)
#ifndef F_PCLKB
#  error "qspi_io.hpp requires F_PCLKB to be defined"
#else
#undef PCLK
#define PCLK F_PCLKB
#endif
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  QSPI 制御クラス
		@param[in]	QSPI	QSPI 定義クラス
		@param[in]	PSEL	ポート候補
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class QSPI, port_map::option PSEL = port_map::option::FIRST>
	class qspi_io {
	public:

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  データ、クロック位相タイプ型
					TYPE1(MODE0): CPOL:0 CPHA:0 @n
					TYPE2(MODE1): CPOL:0 CPHA:1 @n
					TYPE3(MODE2): CPOL:1 CPHA:0 @n
					TYPE4(MODE3): CPOL:1 CPHA:1
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class PHASE : uint8_t {
			TYPE1,  ///< タイプ１
			TYPE2,  ///< タイプ２
			TYPE3,  ///< タイプ３
			TYPE4,  ///< タイプ４ (SD カードアクセス）
		};

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  データ長型
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class DLEN : uint8_t {
			W8  = 0b0111,	///< 8 Bits
			W9  = 0b1000,	///< 9 Bits
			W10 = 0b1001,	///< 10 Bits
			W11 = 0b1010,	///< 11 Bits
			W12 = 0b1011,	///< 12 Bits
			W13 = 0b1100,	///< 13 Bits
			W14 = 0b1101,	///< 14 Bits
			W15 = 0b1110,	///< 15 Bits
			W16 = 0b1111,	///< 16 Bits
			W20 = 0b0000,	///< 20 Bits
			W24 = 0b0001,	///< 24 Bits
			W32 = 0b0011,	///< 32 Bits
		};

	private:

		uint8_t	level_;

		// 便宜上のスリープ
		void sleep_() { asm("nop"); }

		bool clock_div_(uint32_t speed, uint8_t& brdv, uint8_t& spbr) {
///			utils::format("PCLK: %d\n") % static_cast<uint32_t>(PCLK);
			uint32_t br = static_cast<uint32_t>(PCLK) / speed;
			uint8_t dv = 0;
			while(br > 512) {
				br >>= 1;
				++dv;
				if(dv > 3) {
					brdv = 3;
					spbr = 255;
					return false;
				}
			}
			brdv = dv;
			if(br & 1) {
				br >>= 1;
				++br;
			} else {
				br >>= 1;
			}
			if(br) --br;
			spbr = br;
			return true;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		qspi_io() noexcept : level_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  通信速度を設定して、CSI を有効にする
			@param[in]	speed	通信速度
			@param[in]	ctype	クロック位相タイプ
			@param[in]	dlen	データ長設定
			@param[in]	level	割り込みレベル（１～２）、０の場合はポーリング
			@return エラー（速度設定範囲外）なら「false」
		*/
		//-----------------------------------------------------------------//
		bool start(uint32_t speed, PHASE ctype, DLEN dlen, uint8_t level = 0) noexcept
		{
			level_ = level;

			// デバイスを不許可
			QSPI::SPCR = 0x00;

			// ポートを有効にする
			port_map::turn(QSPI::get_peripheral(), true, PSEL);

			bool f = true;
			uint8_t brdv;
			uint8_t spbr;
			if(!clock_div_(speed, brdv, spbr)) {
				f = false;
			}

			power_cfg::turn(QSPI::get_peripheral());

			// 設定
		    QSPI::SPBR = spbr;
			QSPI::SPPCR = 0x00;	// Fixed idle value, disable loop-back
			QSPI::SPSCR = 0x00;	// disable sequence control
			QSPI::SPDCR = 0x20;	// SPLW=1 (long word access)
///			QSPI::SPCMD0 = RSPI::SPCMD0.LSBF.b() | RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100);
			bool cpol = 0;
			bool cpha = 0;
			switch(ctype) {
			case PHASE::TYPE1:
				break;
			case PHASE::TYPE2:
				cpha = 1;
				break;
			case PHASE::TYPE3:
				cpol = 1;
				break;
			case PHASE::TYPE4:
				cpol = 1;
				cpha = 1;
				break;
			default:
				break;
			}
			QSPI::SPCMD0 = QSPI::SPCMD0.BRDV.b(brdv)
				| QSPI::SPCMD0.SPB.b(static_cast<uint8_t>(dlen))
				| QSPI::SPCMD0.CPOL.b(cpol) | QSPI::SPCMD0.CPHA.b(cpha);

			QSPI::SPCR.MSTR = 1;

			QSPI::SPCR.SPE = 1;

			return f;
		}

		//----------------------------------------------------------------//
		/*!
			@brief	リード・ライト
			@param[in]	data	書き込みデータ
			@return 読み出しデータ
		*/
		//----------------------------------------------------------------//
		uint8_t xchg(uint8_t data = 0xff) noexcept
		{
			QSPI::SPDR = static_cast<uint32_t>(data);
			while(QSPI::SPSR.SPRF() == 0) sleep_();
		    return QSPI::SPDR();
		}

		//----------------------------------------------------------------//
		/*!
			@brief	リード・ライト
			@param[in]	data	書き込みデータ
			@return 読み出しデータ
		*/
		//----------------------------------------------------------------//
		uint32_t xchg32(uint32_t data = 0) noexcept
		{
			QSPI::SPDR = static_cast<uint32_t>(data);
			while(QSPI::SPSR.SPRF() == 0) sleep_();
		    return QSPI::SPDR();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  シリアル送信
			@param[in]	src	送信ソース
			@param[in]	cnt	送信サイズ
		*/
		//-----------------------------------------------------------------//
		void send(const uint8_t* src, uint16_t size) noexcept
		{
			auto end = src + size;
			while(src < end) {
				xchg(*src);
				++src;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  シリアル受信
			@param[out]	dst	受信先
			@param[in]	cnt	受信サイズ
		*/
		//-----------------------------------------------------------------//
		void recv(uint8_t* dst, uint16_t size) noexcept
		{
			auto end = dst + size;
			while(dst < end) {
				*dst = xchg();
				++dst;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  RSPIを無効にして、パワーダウンする
			@param[in]	power パワーダウンをしない場合「false」
		*/
		//-----------------------------------------------------------------//
		void destroy(bool power = true) noexcept
		{
			QSPI::SPCR = 0x00;
			port_map::turn(QSPI::get_peripheral(), false);
			if(power) power_cfg::turn(QSPI::get_peripheral(), false);
		}
	};
}
<commit_msg>update: cleanup<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX グループ・QSPI I/O 制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/vect.h"

/// F_PCKx は速度パラメーター計算で必要で、設定が無いとエラーにします。
#if defined(SIG_RX24T)
#  error "qspi_io.hpp not support for RX24T"
#elif defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)
#ifndef F_PCLKB
#  error "qspi_io.hpp requires F_PCLKB to be defined"
#else
#undef PCLK
#define PCLK F_PCLKB
#endif
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  QSPI 制御クラス
		@param[in]	QSPI	QSPI 定義クラス
		@param[in]	PSEL	ポート候補
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class QSPI, port_map::option PSEL = port_map::option::FIRST>
	class qspi_io {
	public:

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  データ、クロック位相タイプ型
					TYPE1(MODE0): CPOL:0 CPHA:0 @n
					TYPE2(MODE1): CPOL:0 CPHA:1 @n
					TYPE3(MODE2): CPOL:1 CPHA:0 @n
					TYPE4(MODE3): CPOL:1 CPHA:1
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class PHASE : uint8_t {
			TYPE1,  ///< タイプ１
			TYPE2,  ///< タイプ２
			TYPE3,  ///< タイプ３
			TYPE4,  ///< タイプ４ (SD カードアクセス）
		};

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  データ長型
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class DLEN : uint8_t {
			W8  = 0b0111,	///< 8 Bits
			W9  = 0b1000,	///< 9 Bits
			W10 = 0b1001,	///< 10 Bits
			W11 = 0b1010,	///< 11 Bits
			W12 = 0b1011,	///< 12 Bits
			W13 = 0b1100,	///< 13 Bits
			W14 = 0b1101,	///< 14 Bits
			W15 = 0b1110,	///< 15 Bits
			W16 = 0b1111,	///< 16 Bits
			W20 = 0b0000,	///< 20 Bits
			W24 = 0b0001,	///< 24 Bits
			W32 = 0b0011,	///< 32 Bits
		};

	private:

		uint8_t	level_;

		// 便宜上のスリープ
		void sleep_() { asm("nop"); }

		bool clock_div_(uint32_t speed, uint8_t& brdv, uint8_t& spbr) {
///			utils::format("PCLK: %d\n") % static_cast<uint32_t>(PCLK);
			uint32_t br = static_cast<uint32_t>(PCLK) / speed;
			uint8_t dv = 0;
			while(br > 512) {
				br >>= 1;
				++dv;
				if(dv > 3) {
					brdv = 3;
					spbr = 255;
					return false;
				}
			}
			brdv = dv;
			if(br & 1) {
				br >>= 1;
				++br;
			} else {
				br >>= 1;
			}
			if(br) --br;
			spbr = br;
			return true;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		qspi_io() noexcept : level_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  通信速度を設定して、CSI を有効にする
			@param[in]	speed	通信速度
			@param[in]	ctype	クロック位相タイプ
			@param[in]	dlen	データ長設定
			@param[in]	level	割り込みレベル（１～２）、０の場合はポーリング
			@return エラー（速度設定範囲外）なら「false」
		*/
		//-----------------------------------------------------------------//
		bool start(uint32_t speed, PHASE ctype, DLEN dlen, uint8_t level = 0) noexcept
		{
			uint8_t brdv;
			uint8_t spbr;
			if(!clock_div_(speed, brdv, spbr)) {
				return false;
			}

			power_cfg::turn(QSPI::get_peripheral());

			// ポートを有効にする
			port_map::turn(QSPI::get_peripheral(), true, PSEL);

			level_ = level;

			// デバイスを不許可
//			QSPI::SPCR = 0x00;

			// 設定
		    QSPI::SPBR = spbr;
			QSPI::SPPCR = 0x00;	// Fixed idle value, disable loop-back
			QSPI::SPSCR = 0x00;	// disable sequence control
			QSPI::SPDCR = 0x20;	// SPLW=1 (long word access)
///			QSPI::SPCMD0 = RSPI::SPCMD0.LSBF.b() | RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100);
			bool cpol = 0;
			bool cpha = 0;
			switch(ctype) {
			case PHASE::TYPE1:
				break;
			case PHASE::TYPE2:
				cpha = 1;
				break;
			case PHASE::TYPE3:
				cpol = 1;
				break;
			case PHASE::TYPE4:
				cpol = 1;
				cpha = 1;
				break;
			default:
				break;
			}
			QSPI::SPCMD0 = QSPI::SPCMD0.BRDV.b(brdv)
				| QSPI::SPCMD0.SPB.b(static_cast<uint8_t>(dlen))
				| QSPI::SPCMD0.CPOL.b(cpol) | QSPI::SPCMD0.CPHA.b(cpha);

			QSPI::SPCR.MSTR = 1;

			QSPI::SPCR.SPE = 1;

			return true;
		}

		//----------------------------------------------------------------//
		/*!
			@brief	リード・ライト
			@param[in]	data	書き込みデータ
			@return 読み出しデータ
		*/
		//----------------------------------------------------------------//
		uint8_t xchg(uint8_t data = 0xff) noexcept
		{
			QSPI::SPDR = static_cast<uint32_t>(data);
			while(QSPI::SPSR.SPRF() == 0) sleep_();
		    return QSPI::SPDR();
		}

		//----------------------------------------------------------------//
		/*!
			@brief	リード・ライト
			@param[in]	data	書き込みデータ
			@return 読み出しデータ
		*/
		//----------------------------------------------------------------//
		uint32_t xchg32(uint32_t data = 0) noexcept
		{
			QSPI::SPDR = static_cast<uint32_t>(data);
			while(QSPI::SPSR.SPRF() == 0) sleep_();
		    return QSPI::SPDR();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  シリアル送信
			@param[in]	src	送信ソース
			@param[in]	cnt	送信サイズ
		*/
		//-----------------------------------------------------------------//
		void send(const uint8_t* src, uint16_t size) noexcept
		{
			auto end = src + size;
			while(src < end) {
				xchg(*src);
				++src;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  シリアル受信
			@param[out]	dst	受信先
			@param[in]	cnt	受信サイズ
		*/
		//-----------------------------------------------------------------//
		void recv(uint8_t* dst, uint16_t size) noexcept
		{
			auto end = dst + size;
			while(dst < end) {
				*dst = xchg();
				++dst;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  RSPIを無効にして、パワーダウンする
			@param[in]	power パワーダウンをしない場合「false」
		*/
		//-----------------------------------------------------------------//
		void destroy(bool power = true) noexcept
		{
			QSPI::SPCR = 0x00;
			port_map::turn(QSPI::get_peripheral(), false);
			if(power) power_cfg::turn(QSPI::get_peripheral(), false);
		}
	};
}
<|endoftext|>


<commit_before><commit_msg>boost no compila<commit_after><|endoftext|>


<commit_before>#include <NfcAdapter.h>
// Drivers
#include <MifareClassic.h>
#include <MifareUltralight.h>

#include <NfcTag.h>

NfcAdapter::NfcAdapter(void)
{
	shield = new Adafruit_NFCShield_I2C(IRQ, RESET);
}

NfcAdapter::~NfcAdapter(void)
{
  delete shield;
}

void NfcAdapter::begin()
{
	shield->begin();

  uint32_t versiondata = shield->getFirmwareVersion();
  if (! versiondata) {
    Serial.print(F("Didn't find PN53x board"));
    while (1); // halt
  }
  // Got ok data, print it out!
  Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  shield->SAMConfig();
}

boolean NfcAdapter::tagPresent()
{
	uint8_t success;
  uidLength = 0;

	success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  // if (success)
  // {
  //   Serial.println("Found an ISO14443A card");
  //   Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
  //   Serial.print("  UID Value: ");
  //   shield->PrintHex(uid, uidLength);
  //   Serial.println("");
  // }

  return success;
}

// TODO return a NfcTag
NdefMessage NfcAdapter::read()
{

  NdefMessage ndefMessage;

	if (uidLength == 4)
  {
    Serial.println(F("Mifare Classic card (4 byte UID)"));

    // NfcTag tag = NfcTag(uid, uidLength, "Mifare Classic", ndefMessage);

    ndefMessage = readMifareClassic(*shield, uid, uidLength);
  }
  else
  {
    // TODO need a better way to determine which driver to use
    // Since I have Mifare Classic cards with 7 byte UIDs
    Serial.println(F("Mifare Ultralight card (7 byte UID)"));

    MifareUltralight ultralight = MifareUltralight(*shield);
    ndefMessage = ultralight.read();
  }
  return ndefMessage;
}

boolean NfcAdapter::write(NdefMessage& ndefMessage)
{
  boolean success;

  if (uidLength == 4)
  {
    writeMifareClassic(*shield, ndefMessage, uid, uidLength);
    success = true; // TODO get status from write!
  }
  else
  {
    Serial.println(F("Unsupported Tag"));
    success = false;
  }
  return success;
}<commit_msg>move includeds to header<commit_after>#include <NfcAdapter.h>

NfcAdapter::NfcAdapter(void)
{
	shield = new Adafruit_NFCShield_I2C(IRQ, RESET);
}

NfcAdapter::~NfcAdapter(void)
{
  delete shield;
}

void NfcAdapter::begin()
{
	shield->begin();

  uint32_t versiondata = shield->getFirmwareVersion();
  if (! versiondata) {
    Serial.print(F("Didn't find PN53x board"));
    while (1); // halt
  }
  // Got ok data, print it out!
  Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  shield->SAMConfig();
}

boolean NfcAdapter::tagPresent()
{
	uint8_t success;
  uidLength = 0;

	success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  // if (success)
  // {
  //   Serial.println("Found an ISO14443A card");
  //   Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
  //   Serial.print("  UID Value: ");
  //   shield->PrintHex(uid, uidLength);
  //   Serial.println("");
  // }

  return success;
}

// TODO return a NfcTag
NdefMessage NfcAdapter::read()
{

  NdefMessage ndefMessage;

	if (uidLength == 4)
  {
    Serial.println(F("Mifare Classic card (4 byte UID)"));

    // NfcTag tag = NfcTag(uid, uidLength, "Mifare Classic", ndefMessage);

    ndefMessage = readMifareClassic(*shield, uid, uidLength);
  }
  else
  {
    // TODO need a better way to determine which driver to use
    // Since I have Mifare Classic cards with 7 byte UIDs
    Serial.println(F("Mifare Ultralight card (7 byte UID)"));

    MifareUltralight ultralight = MifareUltralight(*shield);
    ndefMessage = ultralight.read();
  }
  return ndefMessage;
}

boolean NfcAdapter::write(NdefMessage& ndefMessage)
{
  boolean success;

  if (uidLength == 4)
  {
    writeMifareClassic(*shield, ndefMessage, uid, uidLength);
    success = true; // TODO get status from write!
  }
  else
  {
    Serial.println(F("Unsupported Tag"));
    success = false;
  }
  return success;
}<|endoftext|>


<commit_before>#include "ComputeViscCoeff.h"

template<>
InputParameters validParams<ComputeViscCoeff>()
{
  InputParameters params = validParams<Material>();

  params.addParam<std::string>("viscosity_name", "FIRST_ORDER", "Name of the viscosity definition to use: set to first order by default.");
  // Coupled variables
  params.addRequiredCoupledVar("h"  , "h: water height");
  params.addRequiredCoupledVar("q_x", "x component of momentum");
  params.addCoupledVar("q_y", "y component of momentum");
  // Coupled aux variables
  params.addRequiredCoupledVar("entropy", "entropy function");
  params.addRequiredCoupledVar("F", "x-component of the entropy flux ");
  params.addCoupledVar("G", "y-component of the entropy flux ");
  params.addCoupledVar("B", "bathymetry data");
  params.addParam<Real>("gravity", 9.81, "gravity magnitude");
  // constant parameters:
  //params.addParam<bool>("is_first_order", false, "if true, use the first-order viscosity coefficient");
  params.addParam<double>("Ce"   , 1.0, "Coefficient for entropy viscosity");
  params.addParam<double>("Cjump", 1.0, "Coefficient for jumps");
  params.addParam<double>("Cmax" , 0.5, "Coefficient for first-order viscosity");
  // Userobject:
  params.addRequiredParam<UserObjectName>("eos", "Equation of state");
  // PPS names:
  //params.addParam<std::string>("press_PPS_name", "name of the pps computing pressure");

  return params;
}

ComputeViscCoeff::ComputeViscCoeff(const std::string & name,
                                   InputParameters parameters) :
    Material(name, parameters),
    // Declare viscosity types
    _visc_type("NONE, FIRST_ORDER, ENTROPY, INVALID", getParam<std::string>("viscosity_name")),   // Declare variables
    _h(coupledValue("h")),
    _q_x(coupledValue("q_x")),
    _q_y(_mesh.dimension() == 2 ? coupledValue("q_y") : _zero),
    // entropy:
    _E(coupledValue("entropy")),
    _E_old(coupledValueOld("entropy")),
    _E_older(coupledValueOlder("entropy")),
    // entropy flux:
    _grad_F(coupledGradient("F")),
    _grad_G(_mesh.dimension() == 2 ? coupledGradient("G") : _grad_zero),
    // bathymetry:
    _bathymetry(isCoupled("B") ? coupledValue("B") : _zero),
    _gravity(getParam<Real>("gravity")),
    // Jump of entropy gradients:
    //_jump_grad_entropy(isCoupled("jump_grad_entropy") ? coupledValue("jump_grad_entropy") : _zero),
    // Declare material properties
    _kappa(declareProperty<Real>("kappa")),
    _kappa_max(declareProperty<Real>("kappa_max")),
    _residual(declareProperty<Real>("residual")), // jcr: why declare property for residual?, for output
    // Get constant parameters
    //_is_first_order(getParam<bool>("is_first_order")),
    _Ce(getParam<double>("Ce")),
    _Cjump(getParam<double>("Cjump")),
    _Cmax(getParam<double>("Cmax")),
    // UserObject:
    _eos(getUserObject<HydrostaticPressure>("eos")),
    // PPS name:
    //_entropy_pps_name(getParam<std::string>("PPS_name"))
{
    if (_Ce < 0. || _Ce > 2.)
        mooseError("The coefficient Ce has to be positive and cannot be larger than 2.");
}

void
ComputeViscCoeff::computeQpProperties()
{
  // Determine h (length used in definition of first and second order viscosities):
  Real _h_min = _current_elem->hmin();// /_qrule->get_order(); jcr why called min, not cell?

  // vector q
  RealVectorValue _vector_q( _q_x[_qp], _q_y[_qp], 0. );

  // Compute first order viscosity:
  Real c = std::sqrt(_eos.c2(_h[_qp], _vector_q));
  _kappa_max[_qp] = _Cmax*_h_min*(_vector_q.size()/_h[_qp] + c);

  // Epsilon value normalization of unit vectors:
  Real _eps = std::sqrt(std::numeric_limits<Real>::min());

  // Compute Mach number and velocity variable to use in the normalization parameter:
  // Real entropy_pps = std::max(getPostprocessorValueByName(_entropy_pps_name), eps);

  // Initialize some vector, values, ... for entropy viscosity method:
  RealVectorValue _vector_vel = _vector_q / _h[_qp];

  Real jump=0.;

    // Switch statement over viscosity type:
    switch (_visc_type) {
        case NONE:
            _kappa[_qp] = 0.;
            break;
        case FIRST_ORDER:
            _kappa[_qp] = _kappa_max[_qp];
            break;
        case ENTROPY:
            // Compute the viscosity coefficients:
            if (_t_step == 1) {
                _kappa[_qp] = _kappa_max[_qp];
            }
            else {
                // Weights for BDF2
                Real w0 = _t_step > 2 ? (2.*_dt+_dt_old)/(_dt*(_dt+_dt_old)) : 1. / _dt;
                Real w1 = _t_step > 2 ? -(_dt+_dt_old)/(_dt*_dt_old) : -1. / _dt;
                Real w2 = _t_step > 2 ? _dt/(_dt_old*(_dt+_dt_old)) : 0.;

                // Entropy residual
                Real residual = w0*_E[_qp]+w1*_E_old[_qp]+w2*_E_older[_qp];
                residual += _grad_F[_qp](0)+_grad_G[_qp](1);
                // store at qp
                _residual[_qp] = std::fabs(residual);

                // Compute kappa_e:
                /*if (_isJumpOn)
                    jump = _Cjump*_norm_vel[_qp]*std::max( _jump_grad_entropy[_qp], c*c*_jump_grad_dens[_qp] );
                else
                    jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );*/

                // Froude number (use from Marco while I figure out |s-save|)
                Real Froude = _vector_q.size()/_h[_qp]/std::sqrt(_gravity*(_h[_qp]+_eps));
				Real _norm = _gravity*(_h[_qp]+_bathymetry[_qp]+_eps);
                Real kappa_e = _Ce*_h_min*_h_min*(std::fabs(residual) + jump) / _norm;

                //jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );

                // Compute kappa:
                _kappa[_qp] = std::min( _kappa_max[_qp], kappa_e);
            }
            break;
        default:
            mooseError("The viscosity type entered in the input file is not implemented.");
            break;
    }
}
<commit_msg>use space in enum<commit_after>#include "ComputeViscCoeff.h"

template<>
InputParameters validParams<ComputeViscCoeff>()
{
  InputParameters params = validParams<Material>();

  params.addParam<std::string>("viscosity_name", "FIRST_ORDER", "Name of the viscosity definition to use: set to first order by default.");
  // Coupled variables
  params.addRequiredCoupledVar("h"  , "h: water height");
  params.addRequiredCoupledVar("q_x", "x component of momentum");
  params.addCoupledVar("q_y", "y component of momentum");
  // Coupled aux variables
  params.addRequiredCoupledVar("entropy", "entropy function");
  params.addRequiredCoupledVar("F", "x-component of the entropy flux ");
  params.addCoupledVar("G", "y-component of the entropy flux ");
  params.addCoupledVar("B", "bathymetry data");
  params.addParam<Real>("gravity", 9.81, "gravity magnitude");
  // constant parameters:
  //params.addParam<bool>("is_first_order", false, "if true, use the first-order viscosity coefficient");
  params.addParam<double>("Ce"   , 1.0, "Coefficient for entropy viscosity");
  params.addParam<double>("Cjump", 1.0, "Coefficient for jumps");
  params.addParam<double>("Cmax" , 0.5, "Coefficient for first-order viscosity");
  // Userobject:
  params.addRequiredParam<UserObjectName>("eos", "Equation of state");
  // PPS names:
  //params.addParam<std::string>("press_PPS_name", "name of the pps computing pressure");

  return params;
}

ComputeViscCoeff::ComputeViscCoeff(const std::string & name,
                                   InputParameters parameters) :
    Material(name, parameters),
    // Declare viscosity types
    _visc_type("NONE FIRST_ORDER ENTROPY INVALID", getParam<std::string>("viscosity_name")),   // Declare variables
    _h(coupledValue("h")),
    _q_x(coupledValue("q_x")),
    _q_y(_mesh.dimension() == 2 ? coupledValue("q_y") : _zero),
    // entropy:
    _E(coupledValue("entropy")),
    _E_old(coupledValueOld("entropy")),
    _E_older(coupledValueOlder("entropy")),
    // entropy flux:
    _grad_F(coupledGradient("F")),
    _grad_G(_mesh.dimension() == 2 ? coupledGradient("G") : _grad_zero),
    // bathymetry:
    _bathymetry(isCoupled("B") ? coupledValue("B") : _zero),
    _gravity(getParam<Real>("gravity")),
    // Jump of entropy gradients:
    //_jump_grad_entropy(isCoupled("jump_grad_entropy") ? coupledValue("jump_grad_entropy") : _zero),
    // Declare material properties
    _kappa(declareProperty<Real>("kappa")),
    _kappa_max(declareProperty<Real>("kappa_max")),
    _residual(declareProperty<Real>("residual")), // jcr: why declare property for residual?, for output
    // Get constant parameters
    //_is_first_order(getParam<bool>("is_first_order")),
    _Ce(getParam<double>("Ce")),
    _Cjump(getParam<double>("Cjump")),
    _Cmax(getParam<double>("Cmax")),
    // UserObject:
    _eos(getUserObject<HydrostaticPressure>("eos")),
    // PPS name:
    //_entropy_pps_name(getParam<std::string>("PPS_name"))
{
    if (_Ce < 0. || _Ce > 2.)
        mooseError("The coefficient Ce has to be positive and cannot be larger than 2.");
}

void
ComputeViscCoeff::computeQpProperties()
{
  // Determine h (length used in definition of first and second order viscosities):
  Real _h_min = _current_elem->hmin();// /_qrule->get_order(); jcr why called min, not cell?

  // vector q
  RealVectorValue _vector_q( _q_x[_qp], _q_y[_qp], 0. );

  // Compute first order viscosity:
  Real c = std::sqrt(_eos.c2(_h[_qp], _vector_q));
  _kappa_max[_qp] = _Cmax*_h_min*(_vector_q.size()/_h[_qp] + c);

  // Epsilon value normalization of unit vectors:
  Real _eps = std::sqrt(std::numeric_limits<Real>::min());

  // Compute Mach number and velocity variable to use in the normalization parameter:
  // Real entropy_pps = std::max(getPostprocessorValueByName(_entropy_pps_name), eps);

  // Initialize some vector, values, ... for entropy viscosity method:
  RealVectorValue _vector_vel = _vector_q / _h[_qp];

  Real jump=0.;

    // Switch statement over viscosity type:
    switch (_visc_type) {
        case NONE:
            _kappa[_qp] = 0.;
            break;
        case FIRST_ORDER:
            _kappa[_qp] = _kappa_max[_qp];
            break;
        case ENTROPY:
            // Compute the viscosity coefficients:
            if (_t_step == 1) {
                _kappa[_qp] = _kappa_max[_qp];
            }
            else {
                // Weights for BDF2
                Real w0 = _t_step > 2 ? (2.*_dt+_dt_old)/(_dt*(_dt+_dt_old)) : 1. / _dt;
                Real w1 = _t_step > 2 ? -(_dt+_dt_old)/(_dt*_dt_old) : -1. / _dt;
                Real w2 = _t_step > 2 ? _dt/(_dt_old*(_dt+_dt_old)) : 0.;

                // Entropy residual
                Real residual = w0*_E[_qp]+w1*_E_old[_qp]+w2*_E_older[_qp];
                residual += _grad_F[_qp](0)+_grad_G[_qp](1);
                // store at qp
                _residual[_qp] = std::fabs(residual);

                // Compute kappa_e:
                /*if (_isJumpOn)
                    jump = _Cjump*_norm_vel[_qp]*std::max( _jump_grad_entropy[_qp], c*c*_jump_grad_dens[_qp] );
                else
                    jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );*/

                // Froude number (use from Marco while I figure out |s-save|)
                Real Froude = _vector_q.size()/_h[_qp]/std::sqrt(_gravity*(_h[_qp]+_eps));
				Real _norm = _gravity*(_h[_qp]+_bathymetry[_qp]+_eps);
                Real kappa_e = _Ce*_h_min*_h_min*(std::fabs(residual) + jump) / _norm;

                //jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );

                // Compute kappa:
                _kappa[_qp] = std::min( _kappa_max[_qp], kappa_e);
            }
            break;
        default:
            mooseError("The viscosity type entered in the input file is not implemented.");
            break;
    }
}
<|endoftext|>