text
stringlengths
54
60.6k
<commit_before>/* * Copyright (C) 2008-2012 See the AUTHORS file for details. * Copyright (C) 2006-2007, CNU <[email protected]> (http://cnu.dieplz.net/znc) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include <znc/FileUtils.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Chan.h> #include <znc/Server.h> using std::vector; class CLogMod: public CModule { public: MODCONSTRUCTOR(CLogMod) {} void PutLog(const CString& sLine, const CString& sWindow = "status"); void PutLog(const CString& sLine, const CChan& Channel); void PutLog(const CString& sLine, const CNick& Nick); CString GetServer(); virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual void OnIRCConnected(); virtual void OnIRCDisconnected(); virtual EModRet OnBroadcast(CString& sMessage); virtual void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs); virtual void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage); virtual void OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans); virtual void OnJoin(const CNick& Nick, CChan& Channel); virtual void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage); virtual void OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans); virtual EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic); /* notices */ virtual EModRet OnUserNotice(CString& sTarget, CString& sMessage); virtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage); virtual EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage); /* actions */ virtual EModRet OnUserAction(CString& sTarget, CString& sMessage); virtual EModRet OnPrivAction(CNick& Nick, CString& sMessage); virtual EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage); /* msgs */ virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage); virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage); virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage); private: CString m_sLogPath; }; void CLogMod::PutLog(const CString& sLine, const CString& sWindow /*= "Status"*/) { CString sPath; time_t curtime; time(&curtime); // Generate file name sPath = CUtils::FormatTime(curtime, m_sLogPath, m_pUser->GetTimezone()); if (sPath.empty()) { DEBUG("Could not format log path [" << sPath << "]"); return; } // $WINDOW has to be handled last, since it can contain % sPath.Replace("$NETWORK", (m_pNetwork ? m_pNetwork->GetName() : "znc")); sPath.Replace("$WINDOW", sWindow.Replace_n("/", "?")); sPath.Replace("$USER", (m_pUser ? m_pUser->GetUserName() : "UNKNOWN")); // Check if it's allowed to write in this specific path sPath = CDir::CheckPathPrefix(GetSavePath(), sPath); if (sPath.empty()) { DEBUG("Invalid log path ["<<m_sLogPath<<"]."); return; } CFile LogFile(sPath); CString sLogDir = LogFile.GetDir(); if (!CFile::Exists(sLogDir)) CDir::MakeDir(sLogDir); if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT)) { LogFile.Write(CUtils::FormatTime(curtime, "[%H:%M:%S] ", m_pUser->GetTimezone()) + sLine + "\n"); } else DEBUG("Could not open log file [" << sPath << "]: " << strerror(errno)); } void CLogMod::PutLog(const CString& sLine, const CChan& Channel) { PutLog(sLine, Channel.GetName()); } void CLogMod::PutLog(const CString& sLine, const CNick& Nick) { PutLog(sLine, Nick.GetNick()); } CString CLogMod::GetServer() { CServer* pServer = m_pNetwork->GetCurrentServer(); CString sSSL; if (!pServer) return "(no server)"; if (pServer->IsSSL()) sSSL = "+"; return pServer->GetName() + " " + sSSL + CString(pServer->GetPort()); } bool CLogMod::OnLoad(const CString& sArgs, CString& sMessage) { // Use load parameter as save path m_sLogPath = sArgs; // Add default filename to path if it's a folder if (GetType() == CModInfo::UserModule) { if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == CString::npos || m_sLogPath.find("$NETWORK") == CString::npos) { if (!m_sLogPath.empty()) { m_sLogPath += "/"; } m_sLogPath += "$NETWORK_$WINDOW_%Y%m%d.log"; } } else if (GetType() == CModInfo::NetworkModule) { if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == CString::npos) { if (!m_sLogPath.empty()) { m_sLogPath += "/"; } m_sLogPath += "$WINDOW_%Y%m%d.log"; } } else { if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$USER") == CString::npos || m_sLogPath.find("$WINDOW") == CString::npos || m_sLogPath.find("$NETWORK") == CString::npos) { if (!m_sLogPath.empty()) { m_sLogPath += "/"; } m_sLogPath += "$USER_$NETWORK_$WINDOW_%Y%m%d.log"; } } // Check if it's allowed to write in this path in general m_sLogPath = CDir::CheckPathPrefix(GetSavePath(), m_sLogPath); if (m_sLogPath.empty()) { sMessage = "Invalid log path ["+m_sLogPath+"]."; return false; } else { sMessage = "Logging to ["+m_sLogPath+"]."; return true; } } void CLogMod::OnIRCConnected() { PutLog("Connected to IRC (" + GetServer() + ")"); } void CLogMod::OnIRCDisconnected() { PutLog("Disconnected from IRC (" + GetServer() + ")"); } CModule::EModRet CLogMod::OnBroadcast(CString& sMessage) { PutLog("Broadcast: " + sMessage); return CONTINUE; } void CLogMod::OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs) { PutLog("*** " + OpNick.GetNick() + " sets mode: " + sModes + " " + sArgs, Channel); } void CLogMod::OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) { PutLog("*** " + sKickedNick + " was kicked by " + OpNick.GetNick() + " (" + sMessage + ")", Channel); } void CLogMod::OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans) { for (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan) PutLog("*** Quits: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") (" + sMessage + ")", **pChan); } void CLogMod::OnJoin(const CNick& Nick, CChan& Channel) { PutLog("*** Joins: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ")", Channel); } void CLogMod::OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) { PutLog("*** Parts: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") (" + sMessage + ")", Channel); } void CLogMod::OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans) { for (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan) PutLog("*** " + OldNick.GetNick() + " is now known as " + sNewNick, **pChan); } CModule::EModRet CLogMod::OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) { PutLog("*** " + Nick.GetNick() + " changes topic to '" + sTopic + "'", Channel); return CONTINUE; } /* notices */ CModule::EModRet CLogMod::OnUserNotice(CString& sTarget, CString& sMessage) { if (m_pNetwork) { PutLog("-" + m_pNetwork->GetCurNick() + "- " + sMessage, sTarget); } return CONTINUE; } CModule::EModRet CLogMod::OnPrivNotice(CNick& Nick, CString& sMessage) { PutLog("-" + Nick.GetNick() + "- " + sMessage, Nick); return CONTINUE; } CModule::EModRet CLogMod::OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) { PutLog("-" + Nick.GetNick() + "- " + sMessage, Channel); return CONTINUE; } /* actions */ CModule::EModRet CLogMod::OnUserAction(CString& sTarget, CString& sMessage) { if (m_pNetwork) { PutLog("* " + m_pNetwork->GetCurNick() + " " + sMessage, sTarget); } return CONTINUE; } CModule::EModRet CLogMod::OnPrivAction(CNick& Nick, CString& sMessage) { PutLog("* " + Nick.GetNick() + " " + sMessage, Nick); return CONTINUE; } CModule::EModRet CLogMod::OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) { PutLog("* " + Nick.GetNick() + " " + sMessage, Channel); return CONTINUE; } /* msgs */ CModule::EModRet CLogMod::OnUserMsg(CString& sTarget, CString& sMessage) { if (m_pNetwork) { PutLog("<" + m_pNetwork->GetCurNick() + "> " + sMessage, sTarget); } return CONTINUE; } CModule::EModRet CLogMod::OnPrivMsg(CNick& Nick, CString& sMessage) { PutLog("<" + Nick.GetNick() + "> " + sMessage, Nick); return CONTINUE; } CModule::EModRet CLogMod::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) { PutLog("<" + Nick.GetNick() + "> " + sMessage, Channel); return CONTINUE; } template<> void TModInfo<CLogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetHasArgs(true); Info.SetArgsHelpText("Optional path where to store logs."); } USERMODULEDEFS(CLogMod, "Write IRC logs") <commit_msg>Link log module to wiki.<commit_after>/* * Copyright (C) 2008-2012 See the AUTHORS file for details. * Copyright (C) 2006-2007, CNU <[email protected]> (http://cnu.dieplz.net/znc) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include <znc/FileUtils.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Chan.h> #include <znc/Server.h> using std::vector; class CLogMod: public CModule { public: MODCONSTRUCTOR(CLogMod) {} void PutLog(const CString& sLine, const CString& sWindow = "status"); void PutLog(const CString& sLine, const CChan& Channel); void PutLog(const CString& sLine, const CNick& Nick); CString GetServer(); virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual void OnIRCConnected(); virtual void OnIRCDisconnected(); virtual EModRet OnBroadcast(CString& sMessage); virtual void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs); virtual void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage); virtual void OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans); virtual void OnJoin(const CNick& Nick, CChan& Channel); virtual void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage); virtual void OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans); virtual EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic); /* notices */ virtual EModRet OnUserNotice(CString& sTarget, CString& sMessage); virtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage); virtual EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage); /* actions */ virtual EModRet OnUserAction(CString& sTarget, CString& sMessage); virtual EModRet OnPrivAction(CNick& Nick, CString& sMessage); virtual EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage); /* msgs */ virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage); virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage); virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage); private: CString m_sLogPath; }; void CLogMod::PutLog(const CString& sLine, const CString& sWindow /*= "Status"*/) { CString sPath; time_t curtime; time(&curtime); // Generate file name sPath = CUtils::FormatTime(curtime, m_sLogPath, m_pUser->GetTimezone()); if (sPath.empty()) { DEBUG("Could not format log path [" << sPath << "]"); return; } // $WINDOW has to be handled last, since it can contain % sPath.Replace("$NETWORK", (m_pNetwork ? m_pNetwork->GetName() : "znc")); sPath.Replace("$WINDOW", sWindow.Replace_n("/", "?")); sPath.Replace("$USER", (m_pUser ? m_pUser->GetUserName() : "UNKNOWN")); // Check if it's allowed to write in this specific path sPath = CDir::CheckPathPrefix(GetSavePath(), sPath); if (sPath.empty()) { DEBUG("Invalid log path ["<<m_sLogPath<<"]."); return; } CFile LogFile(sPath); CString sLogDir = LogFile.GetDir(); if (!CFile::Exists(sLogDir)) CDir::MakeDir(sLogDir); if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT)) { LogFile.Write(CUtils::FormatTime(curtime, "[%H:%M:%S] ", m_pUser->GetTimezone()) + sLine + "\n"); } else DEBUG("Could not open log file [" << sPath << "]: " << strerror(errno)); } void CLogMod::PutLog(const CString& sLine, const CChan& Channel) { PutLog(sLine, Channel.GetName()); } void CLogMod::PutLog(const CString& sLine, const CNick& Nick) { PutLog(sLine, Nick.GetNick()); } CString CLogMod::GetServer() { CServer* pServer = m_pNetwork->GetCurrentServer(); CString sSSL; if (!pServer) return "(no server)"; if (pServer->IsSSL()) sSSL = "+"; return pServer->GetName() + " " + sSSL + CString(pServer->GetPort()); } bool CLogMod::OnLoad(const CString& sArgs, CString& sMessage) { // Use load parameter as save path m_sLogPath = sArgs; // Add default filename to path if it's a folder if (GetType() == CModInfo::UserModule) { if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == CString::npos || m_sLogPath.find("$NETWORK") == CString::npos) { if (!m_sLogPath.empty()) { m_sLogPath += "/"; } m_sLogPath += "$NETWORK_$WINDOW_%Y%m%d.log"; } } else if (GetType() == CModInfo::NetworkModule) { if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == CString::npos) { if (!m_sLogPath.empty()) { m_sLogPath += "/"; } m_sLogPath += "$WINDOW_%Y%m%d.log"; } } else { if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$USER") == CString::npos || m_sLogPath.find("$WINDOW") == CString::npos || m_sLogPath.find("$NETWORK") == CString::npos) { if (!m_sLogPath.empty()) { m_sLogPath += "/"; } m_sLogPath += "$USER_$NETWORK_$WINDOW_%Y%m%d.log"; } } // Check if it's allowed to write in this path in general m_sLogPath = CDir::CheckPathPrefix(GetSavePath(), m_sLogPath); if (m_sLogPath.empty()) { sMessage = "Invalid log path ["+m_sLogPath+"]."; return false; } else { sMessage = "Logging to ["+m_sLogPath+"]."; return true; } } void CLogMod::OnIRCConnected() { PutLog("Connected to IRC (" + GetServer() + ")"); } void CLogMod::OnIRCDisconnected() { PutLog("Disconnected from IRC (" + GetServer() + ")"); } CModule::EModRet CLogMod::OnBroadcast(CString& sMessage) { PutLog("Broadcast: " + sMessage); return CONTINUE; } void CLogMod::OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs) { PutLog("*** " + OpNick.GetNick() + " sets mode: " + sModes + " " + sArgs, Channel); } void CLogMod::OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) { PutLog("*** " + sKickedNick + " was kicked by " + OpNick.GetNick() + " (" + sMessage + ")", Channel); } void CLogMod::OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans) { for (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan) PutLog("*** Quits: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") (" + sMessage + ")", **pChan); } void CLogMod::OnJoin(const CNick& Nick, CChan& Channel) { PutLog("*** Joins: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ")", Channel); } void CLogMod::OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) { PutLog("*** Parts: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") (" + sMessage + ")", Channel); } void CLogMod::OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans) { for (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan) PutLog("*** " + OldNick.GetNick() + " is now known as " + sNewNick, **pChan); } CModule::EModRet CLogMod::OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) { PutLog("*** " + Nick.GetNick() + " changes topic to '" + sTopic + "'", Channel); return CONTINUE; } /* notices */ CModule::EModRet CLogMod::OnUserNotice(CString& sTarget, CString& sMessage) { if (m_pNetwork) { PutLog("-" + m_pNetwork->GetCurNick() + "- " + sMessage, sTarget); } return CONTINUE; } CModule::EModRet CLogMod::OnPrivNotice(CNick& Nick, CString& sMessage) { PutLog("-" + Nick.GetNick() + "- " + sMessage, Nick); return CONTINUE; } CModule::EModRet CLogMod::OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) { PutLog("-" + Nick.GetNick() + "- " + sMessage, Channel); return CONTINUE; } /* actions */ CModule::EModRet CLogMod::OnUserAction(CString& sTarget, CString& sMessage) { if (m_pNetwork) { PutLog("* " + m_pNetwork->GetCurNick() + " " + sMessage, sTarget); } return CONTINUE; } CModule::EModRet CLogMod::OnPrivAction(CNick& Nick, CString& sMessage) { PutLog("* " + Nick.GetNick() + " " + sMessage, Nick); return CONTINUE; } CModule::EModRet CLogMod::OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) { PutLog("* " + Nick.GetNick() + " " + sMessage, Channel); return CONTINUE; } /* msgs */ CModule::EModRet CLogMod::OnUserMsg(CString& sTarget, CString& sMessage) { if (m_pNetwork) { PutLog("<" + m_pNetwork->GetCurNick() + "> " + sMessage, sTarget); } return CONTINUE; } CModule::EModRet CLogMod::OnPrivMsg(CNick& Nick, CString& sMessage) { PutLog("<" + Nick.GetNick() + "> " + sMessage, Nick); return CONTINUE; } CModule::EModRet CLogMod::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) { PutLog("<" + Nick.GetNick() + "> " + sMessage, Channel); return CONTINUE; } template<> void TModInfo<CLogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetHasArgs(true); Info.SetArgsHelpText("Optional path where to store logs."); Info.SetWikiPage("log"); } USERMODULEDEFS(CLogMod, "Write IRC logs") <|endoftext|>
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include "gtest/gtest.h" #include <Utils/ResponseUtils.h> #include <Utils/TestUtils.h> #include <hspp/Tasks/BasicTasks/CombatTask.h> #include <hspp/Tasks/BasicTasks/InitAttackCountTask.h> using namespace Hearthstonepp; using namespace TestUtils; class CombatTester { public: CombatTester() : m_gen(CardClass::DRUID, CardClass::ROGUE), m_agent(std::move(m_gen.player1), std::move(m_gen.player2)), m_resp(m_agent), m_combat(m_agent.GetTaskAgent()) { // Do Nothing } std::tuple<Player&, Player&> GetPlayer() { return { m_agent.GetPlayer1(), m_agent.GetPlayer2() }; } void InitAttackCount(PlayerType playerType) { if (playerType == PlayerType::PLAYER1) { m_init.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2()); } else { m_init.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1()); } } void Attack(size_t src, size_t dst, MetaData expected, PlayerType playerType) { auto target = m_resp.Target(src, dst); MetaData result; if (playerType == PlayerType::PLAYER1) { result = m_combat.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2()); } else { result = m_combat.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1()); } EXPECT_EQ(result, expected); TaskMeta meta = target.get(); EXPECT_EQ(meta.id, +TaskID::REQUIRE); } private: PlayerGenerator m_gen; GameAgent m_agent; AutoResponder m_resp; BasicTasks::CombatTask m_combat; BasicTasks::InitAttackCountTask m_init; }; TEST(CombatTask, GetTaskID) { TaskAgent agent; BasicTasks::CombatTask combat(agent); EXPECT_EQ(combat.GetTaskID(), +TaskID::COMBAT); } TEST(CombatTask, Default) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card1 = GenerateMinionCard("minion1", 3, 6); auto card2 = GenerateMinionCard("minion2", 5, 4); player1.field.emplace_back(new Minion(card1)); player2.field.emplace_back(new Minion(card2)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 0, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth); EXPECT_EQ(player2.hero->health, player2.hero->maxHealth - player1.field[0]->GetAttack()); tester.InitAttackCount(PlayerType::PLAYER2); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER2); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(1)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field.size(), static_cast<size_t>(0)); EXPECT_EQ(player2.field.size(), static_cast<size_t>(0)); auto card3 = GenerateMinionCard("minion3", 5, 6); auto card4 = GenerateMinionCard("minion4", 5, 4); player1.field.emplace_back(new Minion(card3)); player2.field.emplace_back(new Minion(card4)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1)); EXPECT_EQ(player2.field.size(), static_cast<size_t>(0)); auto card5 = GenerateMinionCard("minion5", 5, 4); player1.field[0]->SetAttack(1); player2.field.emplace_back(new Minion(card5)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field.size(), static_cast<size_t>(0)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(3)); } TEST(CombatTask, IndexOutOfRange) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion1", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 2, MetaData::COMBAT_DST_IDX_OUT_OF_RANGE, PlayerType::PLAYER1); tester.Attack(2, 1, MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE, PlayerType::PLAYER1); } TEST(CombatTask, Weapon) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion1", 1, 10); player1.hero->weapon = new Weapon(); player1.hero->weapon->SetAttack(4); player1.hero->weapon->SetDurability(2); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(0, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.hero->weapon->GetDurability(), 1); EXPECT_EQ(player2.field[0]->health, 6); } TEST(CombatTask, Charge) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion1", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::CHARGE, 1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); player1.field[0]->SetGameTag(GameTag::CHARGE, 0); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); } TEST(CombatTask, Taunt) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion1", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); player2.field[1]->SetGameTag(GameTag::TAUNT, 1); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); player2.field[1]->SetGameTag(GameTag::TAUNT, 0); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); } TEST(CombatTask, Stealth) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player2.field[0]->SetGameTag(GameTag::STEALTH, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); player1.field[0]->SetGameTag(GameTag::STEALTH, 1); player2.field[0]->SetGameTag(GameTag::STEALTH, 0); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->GetGameTag(GameTag::STEALTH), 0); } TEST(CombatTask, Immune) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::IMMUNE, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, 10); EXPECT_EQ(player2.field[0]->health, 9); } TEST(CombatTask, Windfury) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); player1.field[0]->SetGameTag(GameTag::WINDFURY, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); } TEST(CombatTask, DivineShield) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); player1.field[0]->SetGameTag(GameTag::DIVINE_SHIELD, 1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9)); player2.field[0]->SetGameTag(GameTag::DIVINE_SHIELD, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9)); } TEST(CombatTask, Poisonous) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::POISONOUS, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9)); EXPECT_EQ(player2.field.size(), static_cast<size_t>(0)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::POISONOUS, 0); player2.field[0]->SetGameTag(GameTag::POISONOUS, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field.size(), static_cast<size_t>(0)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9)); } TEST(CombatTask, Freeze) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::FREEZE, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player2.field[0]->GetGameTag(GameTag::FROZEN), 1); tester.InitAttackCount(PlayerType::PLAYER2); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER2); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9)); }<commit_msg>test: Add unit test for weapon that has been destroyed<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include "gtest/gtest.h" #include <Utils/ResponseUtils.h> #include <Utils/TestUtils.h> #include <hspp/Tasks/BasicTasks/CombatTask.h> #include <hspp/Tasks/BasicTasks/InitAttackCountTask.h> using namespace Hearthstonepp; using namespace TestUtils; class CombatTester { public: CombatTester() : m_gen(CardClass::DRUID, CardClass::ROGUE), m_agent(std::move(m_gen.player1), std::move(m_gen.player2)), m_resp(m_agent), m_combat(m_agent.GetTaskAgent()) { // Do Nothing } std::tuple<Player&, Player&> GetPlayer() { return { m_agent.GetPlayer1(), m_agent.GetPlayer2() }; } void InitAttackCount(PlayerType playerType) { if (playerType == PlayerType::PLAYER1) { m_init.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2()); } else { m_init.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1()); } } void Attack(size_t src, size_t dst, MetaData expected, PlayerType playerType) { auto target = m_resp.Target(src, dst); MetaData result; if (playerType == PlayerType::PLAYER1) { result = m_combat.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2()); } else { result = m_combat.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1()); } EXPECT_EQ(result, expected); TaskMeta meta = target.get(); EXPECT_EQ(meta.id, +TaskID::REQUIRE); } private: PlayerGenerator m_gen; GameAgent m_agent; AutoResponder m_resp; BasicTasks::CombatTask m_combat; BasicTasks::InitAttackCountTask m_init; }; TEST(CombatTask, GetTaskID) { TaskAgent agent; BasicTasks::CombatTask combat(agent); EXPECT_EQ(combat.GetTaskID(), +TaskID::COMBAT); } TEST(CombatTask, Default) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card1 = GenerateMinionCard("minion1", 3, 6); auto card2 = GenerateMinionCard("minion2", 5, 4); player1.field.emplace_back(new Minion(card1)); player2.field.emplace_back(new Minion(card2)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 0, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth); EXPECT_EQ(player2.hero->health, player2.hero->maxHealth - player1.field[0]->GetAttack()); tester.InitAttackCount(PlayerType::PLAYER2); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER2); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(1)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field.size(), static_cast<size_t>(0)); EXPECT_EQ(player2.field.size(), static_cast<size_t>(0)); auto card3 = GenerateMinionCard("minion3", 5, 6); auto card4 = GenerateMinionCard("minion4", 5, 4); player1.field.emplace_back(new Minion(card3)); player2.field.emplace_back(new Minion(card4)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1)); EXPECT_EQ(player2.field.size(), static_cast<size_t>(0)); auto card5 = GenerateMinionCard("minion5", 5, 4); player1.field[0]->SetAttack(1); player2.field.emplace_back(new Minion(card5)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field.size(), static_cast<size_t>(0)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(3)); } TEST(CombatTask, IndexOutOfRange) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion1", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 2, MetaData::COMBAT_DST_IDX_OUT_OF_RANGE, PlayerType::PLAYER1); tester.Attack(2, 1, MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE, PlayerType::PLAYER1); } TEST(CombatTask, Weapon) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion1", 1, 10); player1.hero->weapon = new Weapon(); player1.hero->weapon->SetAttack(4); player1.hero->weapon->SetDurability(2); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(0, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.hero->weapon->GetDurability(), 1); EXPECT_EQ(player2.field[0]->health, 6); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(0, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.hero->weapon, nullptr); EXPECT_EQ(player1.hero->GetAttack(), 0); EXPECT_EQ(player2.field[0]->health, 2); } TEST(CombatTask, Charge) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion1", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::CHARGE, 1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); player1.field[0]->SetGameTag(GameTag::CHARGE, 0); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); } TEST(CombatTask, Taunt) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion1", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); player2.field[1]->SetGameTag(GameTag::TAUNT, 1); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); player2.field[1]->SetGameTag(GameTag::TAUNT, 0); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); } TEST(CombatTask, Stealth) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player2.field[0]->SetGameTag(GameTag::STEALTH, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); player1.field[0]->SetGameTag(GameTag::STEALTH, 1); player2.field[0]->SetGameTag(GameTag::STEALTH, 0); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->GetGameTag(GameTag::STEALTH), 0); } TEST(CombatTask, Immune) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::IMMUNE, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, 10); EXPECT_EQ(player2.field[0]->health, 9); } TEST(CombatTask, Windfury) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); player1.field[0]->SetGameTag(GameTag::WINDFURY, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER1); } TEST(CombatTask, DivineShield) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); tester.InitAttackCount(PlayerType::PLAYER1); player1.field[0]->SetGameTag(GameTag::DIVINE_SHIELD, 1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9)); player2.field[0]->SetGameTag(GameTag::DIVINE_SHIELD, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9)); } TEST(CombatTask, Poisonous) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::POISONOUS, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9)); EXPECT_EQ(player2.field.size(), static_cast<size_t>(0)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::POISONOUS, 0); player2.field[0]->SetGameTag(GameTag::POISONOUS, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player1.field.size(), static_cast<size_t>(0)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9)); } TEST(CombatTask, Freeze) { CombatTester tester; auto [player1, player2] = tester.GetPlayer(); auto card = GenerateMinionCard("minion", 1, 10); player1.field.emplace_back(new Minion(card)); player2.field.emplace_back(new Minion(card)); player1.field[0]->SetGameTag(GameTag::FREEZE, 1); tester.InitAttackCount(PlayerType::PLAYER1); tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, PlayerType::PLAYER1); EXPECT_EQ(player2.field[0]->GetGameTag(GameTag::FROZEN), 1); tester.InitAttackCount(PlayerType::PLAYER2); tester.Attack(1, 1, MetaData::COMBAT_SOURCE_CANT_ATTACK, PlayerType::PLAYER2); EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9)); EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9)); }<|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // create_executor.cpp // // Identification: src/executor/create_executor.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "executor/create_executor.h" #include "catalog/catalog.h" #include "common/logger.h" #include "concurrency/transaction.h" #include "executor/executor_context.h" #include "planner/create_plan.h" #include "commands/trigger.h" #include "storage/data_table.h" namespace peloton { namespace executor { // Constructor for drop executor CreateExecutor::CreateExecutor(const planner::AbstractPlan *node, ExecutorContext *executor_context) : AbstractExecutor(node, executor_context) { context_ = executor_context; } // Initialize executer // Nothing to initialize now bool CreateExecutor::DInit() { LOG_TRACE("Initializing Create Executer..."); LOG_TRACE("Create Executer initialized!"); return true; } bool CreateExecutor::DExecute() { LOG_TRACE("Executing Create..."); const planner::CreatePlan &node = GetPlanNode<planner::CreatePlan>(); auto current_txn = context_->GetTransaction(); // Check if query was for creating table if (node.GetCreateType() == CreateType::TABLE) { std::string table_name = node.GetTableName(); auto database_name = node.GetDatabaseName(); std::unique_ptr<catalog::Schema> schema(node.GetSchema()); ResultType result = catalog::Catalog::GetInstance()->CreateTable( database_name, table_name, std::move(schema), current_txn); current_txn->SetResult(result); if (current_txn->GetResult() == ResultType::SUCCESS) { LOG_TRACE("Creating table succeeded!"); } else if (current_txn->GetResult() == ResultType::FAILURE) { LOG_TRACE("Creating table failed!"); } else { LOG_TRACE("Result is: %s", ResultTypeToString(current_txn->GetResult()).c_str()); } } // Check if query was for creating index if (node.GetCreateType() == CreateType::INDEX) { std::string table_name = node.GetTableName(); std::string index_name = node.GetIndexName(); bool unique_flag = node.IsUnique(); IndexType index_type = node.GetIndexType(); auto index_attrs = node.GetIndexAttributes(); ResultType result = catalog::Catalog::GetInstance()->CreateIndex( DEFAULT_DB_NAME, table_name, index_attrs, index_name, unique_flag, index_type, current_txn); current_txn->SetResult(result); if (current_txn->GetResult() == ResultType::SUCCESS) { LOG_TRACE("Creating table succeeded!"); } else if (current_txn->GetResult() == ResultType::FAILURE) { LOG_TRACE("Creating table failed!"); } else { LOG_TRACE("Result is: %s", ResultTypeToString(current_txn->GetResult()).c_str()); } } // Check if query was for creating trigger if (node.GetCreateType() == CreateType::TRIGGER) { LOG_INFO("enter CreateType::TRIGGER"); std::string database_name = node.GetDatabaseName(); std::string table_name = node.GetTableName(); std::string trigger_name = node.GetTriggerName(); // std::unique_ptr<catalog::Schema> schema(node.GetSchema()); commands::Trigger newTrigger(node); // // new approach: add trigger to the data_table instance directly // storage::DataTable *target_table = // catalog::Catalog::GetInstance()->GetTableWithName(database_name, // table_name); // target_table->AddTrigger(newTrigger); // durable trigger: insert the information of this trigger in the trigger catalog table oid_t database_oid = catalog::DatabaseCatalog::GetInstance()->GetDatabaseOid(database_name, current_txn); oid_t table_oid = catalog::TableCatalog::GetInstance()->GetTableOid(table_name, database_oid, current_txn); auto time_since_epoch = std::chrono::system_clock::now().time_since_epoch(); auto time_stamp = std::chrono::duration_cast<std::chrono::seconds>( time_since_epoch).count(); LOG_INFO("1"); catalog::TriggerCatalog::GetInstance()->InsertTrigger(trigger_name, database_oid, table_oid, newTrigger.GetTriggerType(), newTrigger.GetFireCondition(), newTrigger.GetFireFunction(), newTrigger.GetFireFunctionArgs(), time_stamp, pool_.get(), current_txn); LOG_INFO("2"); // ask target table to update its trigger list variable storage::DataTable *target_table = catalog::Catalog::GetInstance()->GetTableWithName(database_name, table_name); target_table->UpdateTriggerListFromCatalog(current_txn); // // debug: // auto trigger_list = catalog::TriggerCatalog::GetInstance()->GetTriggers(database_oid, table_oid, // newTrigger.GetTriggerType(), current_txn); // if (trigger_list == nullptr) { // LOG_INFO("nullptr"); // } else { // LOG_INFO("size of trigger list in target table: %d", trigger_list->GetTriggerListSize()); // } // LOG_INFO("trigger type=%d", newTrigger.GetTriggerType()); // LOG_INFO("3"); // if (current_txn->GetResult() == ResultType::SUCCESS) { // LOG_TRACE("Creating trigger succeeded!"); // } else if (current_txn->GetResult() == ResultType::FAILURE) { // LOG_TRACE("Creating trigger failed!"); // } else { // LOG_TRACE("Result is: %s", ResultTypeToString( // current_txn->GetResult()).c_str()); // } // hardcode SUCCESS result for current_txn current_txn->SetResult(ResultType::SUCCESS); } return false; } } // namespace executor } // namespace peloton <commit_msg>fix minor bugs<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // create_executor.cpp // // Identification: src/executor/create_executor.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "executor/create_executor.h" #include "catalog/catalog.h" #include "common/logger.h" #include "concurrency/transaction.h" #include "executor/executor_context.h" #include "planner/create_plan.h" #include "commands/trigger.h" #include "storage/data_table.h" namespace peloton { namespace executor { // Constructor for drop executor CreateExecutor::CreateExecutor(const planner::AbstractPlan *node, ExecutorContext *executor_context) : AbstractExecutor(node, executor_context) { context_ = executor_context; } // Initialize executer // Nothing to initialize now bool CreateExecutor::DInit() { LOG_TRACE("Initializing Create Executer..."); LOG_TRACE("Create Executer initialized!"); return true; } bool CreateExecutor::DExecute() { LOG_TRACE("Executing Create..."); const planner::CreatePlan &node = GetPlanNode<planner::CreatePlan>(); auto current_txn = context_->GetTransaction(); // Check if query was for creating table if (node.GetCreateType() == CreateType::TABLE) { std::string table_name = node.GetTableName(); auto database_name = node.GetDatabaseName(); std::unique_ptr<catalog::Schema> schema(node.GetSchema()); ResultType result = catalog::Catalog::GetInstance()->CreateTable( database_name, table_name, std::move(schema), current_txn); current_txn->SetResult(result); if (current_txn->GetResult() == ResultType::SUCCESS) { LOG_TRACE("Creating table succeeded!"); } else if (current_txn->GetResult() == ResultType::FAILURE) { LOG_TRACE("Creating table failed!"); } else { LOG_TRACE("Result is: %s", ResultTypeToString(current_txn->GetResult()).c_str()); } } // Check if query was for creating index if (node.GetCreateType() == CreateType::INDEX) { std::string table_name = node.GetTableName(); std::string index_name = node.GetIndexName(); bool unique_flag = node.IsUnique(); IndexType index_type = node.GetIndexType(); auto index_attrs = node.GetIndexAttributes(); ResultType result = catalog::Catalog::GetInstance()->CreateIndex( DEFAULT_DB_NAME, table_name, index_attrs, index_name, unique_flag, index_type, current_txn); current_txn->SetResult(result); if (current_txn->GetResult() == ResultType::SUCCESS) { LOG_TRACE("Creating table succeeded!"); } else if (current_txn->GetResult() == ResultType::FAILURE) { LOG_TRACE("Creating table failed!"); } else { LOG_TRACE("Result is: %s", ResultTypeToString(current_txn->GetResult()).c_str()); } } // Check if query was for creating trigger if (node.GetCreateType() == CreateType::TRIGGER) { LOG_INFO("enter CreateType::TRIGGER"); std::string database_name = node.GetDatabaseName(); std::string table_name = node.GetTableName(); std::string trigger_name = node.GetTriggerName(); // std::unique_ptr<catalog::Schema> schema(node.GetSchema()); commands::Trigger newTrigger(node); // // new approach: add trigger to the data_table instance directly // storage::DataTable *target_table = // catalog::Catalog::GetInstance()->GetTableWithName(database_name, // table_name); // target_table->AddTrigger(newTrigger); // durable trigger: insert the information of this trigger in the trigger catalog table oid_t database_oid = catalog::DatabaseCatalog::GetInstance()->GetDatabaseOid(database_name, current_txn); oid_t table_oid = catalog::TableCatalog::GetInstance()->GetTableOid(table_name, database_oid, current_txn); auto time_since_epoch = std::chrono::system_clock::now().time_since_epoch(); auto time_stamp = std::chrono::duration_cast<std::chrono::seconds>( time_since_epoch).count(); LOG_INFO("1"); catalog::TriggerCatalog::GetInstance()->InsertTrigger(trigger_name, database_oid, table_oid, newTrigger.GetTriggerType(), newTrigger.GetWhen(), newTrigger.GetFuncname(), newTrigger.GetArgs(), time_stamp, pool_.get(), current_txn); LOG_INFO("2"); // ask target table to update its trigger list variable storage::DataTable *target_table = catalog::Catalog::GetInstance()->GetTableWithName(database_name, table_name); target_table->UpdateTriggerListFromCatalog(current_txn); // // debug: // auto trigger_list = catalog::TriggerCatalog::GetInstance()->GetTriggers(database_oid, table_oid, // newTrigger.GetTriggerType(), current_txn); // if (trigger_list == nullptr) { // LOG_INFO("nullptr"); // } else { // LOG_INFO("size of trigger list in target table: %d", trigger_list->GetTriggerListSize()); // } // LOG_INFO("trigger type=%d", newTrigger.GetTriggerType()); // LOG_INFO("3"); // if (current_txn->GetResult() == ResultType::SUCCESS) { // LOG_TRACE("Creating trigger succeeded!"); // } else if (current_txn->GetResult() == ResultType::FAILURE) { // LOG_TRACE("Creating trigger failed!"); // } else { // LOG_TRACE("Result is: %s", ResultTypeToString( // current_txn->GetResult()).c_str()); // } // hardcode SUCCESS result for current_txn current_txn->SetResult(ResultType::SUCCESS); } return false; } } // namespace executor } // namespace peloton <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: PreparedStatement.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2004-11-09 12:18:07 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_SQL_PREPAREDSTATEMENT_HXX_ #define _CONNECTIVITY_JAVA_SQL_PREPAREDSTATEMENT_HXX_ #ifndef _CONNECTIVITY_JAVA_SQL_STATEMENT_HXX_ #include "java/sql/Statement.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XPREPAREDSTATEMENT_HPP_ #include <com/sun/star/sdbc/XPreparedStatement.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XPARAMETERS_HPP_ #include <com/sun/star/sdbc/XParameters.hpp> #endif // #include <com/sun/star/sdbc/XClearParameters.hpp> #ifndef _COM_SUN_STAR_SDBC_XPREPAREDBATCHEXECUTION_HPP_ #include <com/sun/star/sdbc/XPreparedBatchExecution.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_ #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif namespace connectivity { //************************************************************** //************ Class: java.sql.PreparedStatement //************************************************************** class java_sql_PreparedStatement : public OStatement_BASE2, public ::com::sun::star::sdbc::XPreparedStatement, public ::com::sun::star::sdbc::XResultSetMetaDataSupplier, public ::com::sun::star::sdbc::XParameters, public ::com::sun::star::sdbc::XPreparedBatchExecution, public ::com::sun::star::lang::XServiceInfo { protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); virtual void createStatement(JNIEnv* _pEnv); virtual ~java_sql_PreparedStatement(); public: DECLARE_SERVICE_INFO(); static jclass getMyClass(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_sql_PreparedStatement( JNIEnv * pEnv, java_sql_Connection* _pCon,const ::rtl::OUString& sql ); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // XPreparedStatement virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL executeUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL execute( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XParameters virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearParameters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XPreparedBatchExecution virtual void SAL_CALL addBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL executeBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XResultSetMetaDataSupplier virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } #endif // _CONNECTIVITY_JAVA_SQL_PREPAREDSTATEMENT_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.7.106); FILE MERGED 2005/09/05 17:25:34 rt 1.7.106.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PreparedStatement.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-08 07:22:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_SQL_PREPAREDSTATEMENT_HXX_ #define _CONNECTIVITY_JAVA_SQL_PREPAREDSTATEMENT_HXX_ #ifndef _CONNECTIVITY_JAVA_SQL_STATEMENT_HXX_ #include "java/sql/Statement.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XPREPAREDSTATEMENT_HPP_ #include <com/sun/star/sdbc/XPreparedStatement.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XPARAMETERS_HPP_ #include <com/sun/star/sdbc/XParameters.hpp> #endif // #include <com/sun/star/sdbc/XClearParameters.hpp> #ifndef _COM_SUN_STAR_SDBC_XPREPAREDBATCHEXECUTION_HPP_ #include <com/sun/star/sdbc/XPreparedBatchExecution.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_ #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif namespace connectivity { //************************************************************** //************ Class: java.sql.PreparedStatement //************************************************************** class java_sql_PreparedStatement : public OStatement_BASE2, public ::com::sun::star::sdbc::XPreparedStatement, public ::com::sun::star::sdbc::XResultSetMetaDataSupplier, public ::com::sun::star::sdbc::XParameters, public ::com::sun::star::sdbc::XPreparedBatchExecution, public ::com::sun::star::lang::XServiceInfo { protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); virtual void createStatement(JNIEnv* _pEnv); virtual ~java_sql_PreparedStatement(); public: DECLARE_SERVICE_INFO(); static jclass getMyClass(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_sql_PreparedStatement( JNIEnv * pEnv, java_sql_Connection* _pCon,const ::rtl::OUString& sql ); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // XPreparedStatement virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL executeUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL execute( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XParameters virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearParameters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XPreparedBatchExecution virtual void SAL_CALL addBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL executeBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XResultSetMetaDataSupplier virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } #endif // _CONNECTIVITY_JAVA_SQL_PREPAREDSTATEMENT_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ResultSetMetaData.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:14:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_ #define _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_ #ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_ #include "java/lang/Object.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_ #include <com/sun/star/sdbc/XResultSetMetaData.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif namespace connectivity { //************************************************************** //************ Class: java.sql.ResultSetMetaData //************************************************************** class java_sql_ResultSetMetaData : public ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>, public java_lang_Object { protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); public: static jclass getMyClass(); virtual ~java_sql_ResultSetMetaData(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_sql_ResultSetMetaData( JNIEnv * pEnv, jobject myObj ) : java_lang_Object( pEnv, myObj ){} virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } #endif // _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_ <commit_msg>INTEGRATION: CWS hsqldb (1.1.1.1.244); FILE MERGED 2004/09/22 11:31:28 oj 1.1.1.1.244.1: #i33348# performance fixes<commit_after>/************************************************************************* * * $RCSfile: ResultSetMetaData.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-11-09 12:18:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_ #define _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_ #ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_ #include "java/lang/Object.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_ #include <com/sun/star/sdbc/XResultSetMetaData.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif namespace connectivity { //************************************************************** //************ Class: java.sql.ResultSetMetaData //************************************************************** class java_sql_ResultSetMetaData : public ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>, public java_lang_Object { protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); virtual ~java_sql_ResultSetMetaData(); public: static jclass getMyClass(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_sql_ResultSetMetaData( JNIEnv * pEnv, jobject myObj ); virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } #endif // _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_ <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 Estimation and Control Library (ECL). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name ECL nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file terrain_estimator.cpp * Function for fusing rangefinder measurements to estimate terrain vertical position/ * * @author Paul Riseborough <[email protected]> * */ #include "ekf.h" #include "mathlib.h" bool Ekf::initHagl() { // get most recent range measurement from buffer rangeSample latest_measurement = _range_buffer.get_newest(); if ((_time_last_imu - latest_measurement.time_us) < 2e5) { // if we have a fresh measurement, use it to initialise the terrain estimator _terrain_vpos = _state.pos(2) + latest_measurement.rng; // initialise state variance to variance of measurement _terrain_var = sq(_params.range_noise); // success return true; } else if (!_in_air) { // if on ground we assume a ground clearance _terrain_vpos = _state.pos(2) + _params.rng_gnd_clearance; // Use the ground clearance value as our uncertainty _terrain_var = sq(_params.rng_gnd_clearance); // ths is a guess return false; } else { // no information - cannot initialise return false; } } void Ekf::predictHagl() { // predict the state variance growth // the state is the vertical position of the terrain underneath the vehicle _terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_p_noise); // limit the variance to prevent it becoming badly conditioned _terrain_var = math::constrain(_terrain_var, 0.0f, 1e4f); } void Ekf::fuseHagl() { // If the vehicle is excessively tilted, do not try to fuse range finder observations if (_R_prev(2, 2) > 0.7071f) { // get a height above ground measurement from the range finder assuming a flat earth float meas_hagl = _range_sample_delayed.rng * _R_prev(2, 2); // predict the hagl from the vehicle position and terrain height float pred_hagl = _terrain_vpos - _state.pos(2); // calculate the innovation _hagl_innov = pred_hagl - meas_hagl; // calculate the observation variance adding the variance of the vehicles own height uncertainty and factoring in the effect of tilt on measurement error float obs_variance = fmaxf(P[8][8], 0.0f) + sq(_params.range_noise / _R_prev(2, 2)); // calculate the innovation variance - limiting it to prevent a badly conditioned fusion _hagl_innov_var = fmaxf(_terrain_var + obs_variance, obs_variance); // perform an innovation consistency check and only fuse data if it passes float gate_size = fmaxf(_params.range_innov_gate, 1.0f); float test_ratio = sq(_hagl_innov) / (sq(gate_size) * _hagl_innov_var); if (test_ratio <= 1.0f) { // calculate the Kalman gain float gain = obs_variance / _hagl_innov_var; // correct the state _terrain_vpos -= gain * _hagl_innov; // correct the variance _terrain_var = fmaxf(_terrain_var * (1.0f - gain), 0.0f); // record last successful fusion time _time_last_hagl_fuse = _time_last_imu; } } else { return; } } // return true if the estimate is fresh // return the estimated vertical position of the terrain relative to the NED origin bool Ekf::get_terrain_vert_pos(float *ret) { memcpy(ret, &_terrain_vpos, sizeof(float)); // The height is useful if the uncertainty in terrain height is significantly smaller than than the estimated height above terrain bool accuracy_useful = (sqrtf(_terrain_var) < 0.2f * fmaxf((_terrain_vpos - _state.pos(2)), _params.rng_gnd_clearance)); if (_time_last_imu - _time_last_hagl_fuse < 1e6 || accuracy_useful) { return true; } else { return false; } } void Ekf::get_hagl_innov(float *hagl_innov) { memcpy(hagl_innov, &_hagl_innov, sizeof(_hagl_innov)); } void Ekf::get_hagl_innov_var(float *hagl_innov_var) { memcpy(hagl_innov_var, &_hagl_innov_var, sizeof(_hagl_innov_var)); } <commit_msg>EKF: Fix bug in calculation of terrain estimator Kalman gain<commit_after>/**************************************************************************** * * Copyright (c) 2015 Estimation and Control Library (ECL). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name ECL nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file terrain_estimator.cpp * Function for fusing rangefinder measurements to estimate terrain vertical position/ * * @author Paul Riseborough <[email protected]> * */ #include "ekf.h" #include "mathlib.h" bool Ekf::initHagl() { // get most recent range measurement from buffer rangeSample latest_measurement = _range_buffer.get_newest(); if ((_time_last_imu - latest_measurement.time_us) < 2e5) { // if we have a fresh measurement, use it to initialise the terrain estimator _terrain_vpos = _state.pos(2) + latest_measurement.rng; // initialise state variance to variance of measurement _terrain_var = sq(_params.range_noise); // success return true; } else if (!_in_air) { // if on ground we assume a ground clearance _terrain_vpos = _state.pos(2) + _params.rng_gnd_clearance; // Use the ground clearance value as our uncertainty _terrain_var = sq(_params.rng_gnd_clearance); // ths is a guess return false; } else { // no information - cannot initialise return false; } } void Ekf::predictHagl() { // predict the state variance growth // the state is the vertical position of the terrain underneath the vehicle _terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_p_noise); // limit the variance to prevent it becoming badly conditioned _terrain_var = math::constrain(_terrain_var, 0.0f, 1e4f); } void Ekf::fuseHagl() { // If the vehicle is excessively tilted, do not try to fuse range finder observations if (_R_prev(2, 2) > 0.7071f) { // get a height above ground measurement from the range finder assuming a flat earth float meas_hagl = _range_sample_delayed.rng * _R_prev(2, 2); // predict the hagl from the vehicle position and terrain height float pred_hagl = _terrain_vpos - _state.pos(2); // calculate the innovation _hagl_innov = pred_hagl - meas_hagl; // calculate the observation variance adding the variance of the vehicles own height uncertainty and factoring in the effect of tilt on measurement error float obs_variance = fmaxf(P[8][8], 0.0f) + sq(_params.range_noise / _R_prev(2, 2)); // calculate the innovation variance - limiting it to prevent a badly conditioned fusion _hagl_innov_var = fmaxf(_terrain_var + obs_variance, obs_variance); // perform an innovation consistency check and only fuse data if it passes float gate_size = fmaxf(_params.range_innov_gate, 1.0f); float test_ratio = sq(_hagl_innov) / (sq(gate_size) * _hagl_innov_var); if (test_ratio <= 1.0f) { // calculate the Kalman gain float gain = _terrain_var / _hagl_innov_var; // correct the state _terrain_vpos -= gain * _hagl_innov; // correct the variance _terrain_var = fmaxf(_terrain_var * (1.0f - gain), 0.0f); // record last successful fusion time _time_last_hagl_fuse = _time_last_imu; } } else { return; } } // return true if the estimate is fresh // return the estimated vertical position of the terrain relative to the NED origin bool Ekf::get_terrain_vert_pos(float *ret) { memcpy(ret, &_terrain_vpos, sizeof(float)); // The height is useful if the uncertainty in terrain height is significantly smaller than than the estimated height above terrain bool accuracy_useful = (sqrtf(_terrain_var) < 0.2f * fmaxf((_terrain_vpos - _state.pos(2)), _params.rng_gnd_clearance)); if (_time_last_imu - _time_last_hagl_fuse < 1e6 || accuracy_useful) { return true; } else { return false; } } void Ekf::get_hagl_innov(float *hagl_innov) { memcpy(hagl_innov, &_hagl_innov, sizeof(_hagl_innov)); } void Ekf::get_hagl_innov_var(float *hagl_innov_var) { memcpy(hagl_innov_var, &_hagl_innov_var, sizeof(_hagl_innov_var)); } <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sync/internal_api/public/base/cancelation_signal.h" #include "base/bind.h" #include "base/message_loop/message_loop.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "sync/internal_api/public/base/cancelation_observer.h" #include "testing/gtest/include/gtest/gtest.h" namespace syncer { class BlockingTask : public CancelationObserver { public: BlockingTask(CancelationSignal* cancel_signal); virtual ~BlockingTask(); // Starts the |exec_thread_| and uses it to execute DoRun(). void RunAsync(base::WaitableEvent* task_done_signal); // Blocks until canceled. Signals |task_done_signal| when finished. void Run(base::WaitableEvent* task_done_signal); // Implementation of CancelationObserver. // Wakes up the thread blocked in Run(). virtual void OnSignalReceived() OVERRIDE; // Checks if we ever did successfully start waiting for |event_|. Be careful // with this. The flag itself is thread-unsafe, and the event that flips it // is racy. bool WasStarted(); private: base::WaitableEvent event_; base::Thread exec_thread_; CancelationSignal* cancel_signal_; bool was_started_; }; BlockingTask::BlockingTask(CancelationSignal* cancel_signal) : event_(true, false), exec_thread_("BlockingTaskBackgroundThread"), cancel_signal_(cancel_signal), was_started_(false) { } BlockingTask::~BlockingTask() {} void BlockingTask::RunAsync(base::WaitableEvent* task_done_signal) { exec_thread_.Start(); exec_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&BlockingTask::Run, base::Unretained(this), base::Unretained(task_done_signal))); } void BlockingTask::Run(base::WaitableEvent* task_done_signal) { if (cancel_signal_->TryRegisterHandler(this)) { DCHECK(!event_.IsSignaled()); was_started_ = true; event_.Wait(); } task_done_signal->Signal(); } void BlockingTask::OnSignalReceived() { event_.Signal(); } bool BlockingTask::WasStarted() { return was_started_; } class CancelationSignalTest : public ::testing::Test { public: CancelationSignalTest(); virtual ~CancelationSignalTest(); // Starts the blocking task on a background thread. void StartBlockingTask(); // Cancels the blocking task. void CancelBlocking(); // Verifies that the background task is not running. This could be beacause // it was canceled early or because it was canceled after it was started. // // This method may block for a brief period of time while waiting for the // background thread to make progress. bool VerifyTaskDone(); // Verifies that the background task was canceled early. // // This method may block for a brief period of time while waiting for the // background thread to make progress. bool VerifyTaskNotStarted(); private: base::MessageLoop main_loop_; CancelationSignal signal_; base::WaitableEvent task_done_event_; BlockingTask blocking_task_; }; CancelationSignalTest::CancelationSignalTest() : task_done_event_(false, false), blocking_task_(&signal_) {} CancelationSignalTest::~CancelationSignalTest() {} void CancelationSignalTest::StartBlockingTask() { blocking_task_.RunAsync(&task_done_event_); } void CancelationSignalTest::CancelBlocking() { signal_.Signal(); } bool CancelationSignalTest::VerifyTaskDone() { // Wait until BlockingTask::Run() has finished. task_done_event_.Wait(); return true; } bool CancelationSignalTest::VerifyTaskNotStarted() { // Wait until BlockingTask::Run() has finished. task_done_event_.Wait(); // Verify the background thread never started blocking. return !blocking_task_.WasStarted(); } class FakeCancelationObserver : public CancelationObserver { virtual void OnSignalReceived() OVERRIDE { } }; TEST(CancelationSignalTest_SingleThread, CheckFlags) { FakeCancelationObserver observer; CancelationSignal signal; EXPECT_FALSE(signal.IsSignalled()); signal.Signal(); EXPECT_TRUE(signal.IsSignalled()); EXPECT_FALSE(signal.TryRegisterHandler(&observer)); } // Send the cancelation signal before the task is started. This will ensure // that the task will never be attempted. TEST_F(CancelationSignalTest, CancelEarly) { CancelBlocking(); StartBlockingTask(); EXPECT_TRUE(VerifyTaskNotStarted()); } // This test is flaky on iOS and Mac; see http://crbug.com/340360 #if defined(OS_IOS) || defined(OS_MACOSX) #define MAYBE_Cancel DISABLED_Cancel #else #define MAYBE_Cancel Cancel #endif // Send the cancelation signal after the request to start the task has been // posted. This is racy. The signal to stop may arrive before the signal to // run the task. If that happens, we end up with another instance of the // CancelEarly test defined earlier. If the signal requesting a stop arrives // after the task has been started, it should end up stopping the task. TEST_F(CancelationSignalTest, MAYBE_Cancel) { StartBlockingTask(); CancelBlocking(); EXPECT_TRUE(VerifyTaskDone()); } } // namespace syncer <commit_msg>Fix CancelationSignalTest.Cancel<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sync/internal_api/public/base/cancelation_signal.h" #include "base/bind.h" #include "base/message_loop/message_loop.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "sync/internal_api/public/base/cancelation_observer.h" #include "testing/gtest/include/gtest/gtest.h" namespace syncer { class BlockingTask : public CancelationObserver { public: BlockingTask(CancelationSignal* cancel_signal); virtual ~BlockingTask(); // Starts the |exec_thread_| and uses it to execute DoRun(). void RunAsync(base::WaitableEvent* task_start_signal, base::WaitableEvent* task_done_signal); // Blocks until canceled. Signals |task_done_signal| when finished (either // via early cancel or cancel after start). Signals |task_start_signal| if // and when the task starts successfully (which will not happen if the task // was cancelled early). void Run(base::WaitableEvent* task_start_signal, base::WaitableEvent* task_done_signal); // Implementation of CancelationObserver. // Wakes up the thread blocked in Run(). virtual void OnSignalReceived() OVERRIDE; // Checks if we ever did successfully start waiting for |event_|. Be careful // with this. The flag itself is thread-unsafe, and the event that flips it // is racy. bool WasStarted(); private: base::WaitableEvent event_; base::Thread exec_thread_; CancelationSignal* cancel_signal_; bool was_started_; }; BlockingTask::BlockingTask(CancelationSignal* cancel_signal) : event_(true, false), exec_thread_("BlockingTaskBackgroundThread"), cancel_signal_(cancel_signal), was_started_(false) { } BlockingTask::~BlockingTask() { if (was_started_) { cancel_signal_->UnregisterHandler(this); } } void BlockingTask::RunAsync(base::WaitableEvent* task_start_signal, base::WaitableEvent* task_done_signal) { exec_thread_.Start(); exec_thread_.message_loop()->PostTask( FROM_HERE, base::Bind(&BlockingTask::Run, base::Unretained(this), base::Unretained(task_start_signal), base::Unretained(task_done_signal))); } void BlockingTask::Run( base::WaitableEvent* task_start_signal, base::WaitableEvent* task_done_signal) { if (cancel_signal_->TryRegisterHandler(this)) { DCHECK(!event_.IsSignaled()); was_started_ = true; task_start_signal->Signal(); event_.Wait(); } task_done_signal->Signal(); } void BlockingTask::OnSignalReceived() { event_.Signal(); } bool BlockingTask::WasStarted() { return was_started_; } class CancelationSignalTest : public ::testing::Test { public: CancelationSignalTest(); virtual ~CancelationSignalTest(); // Starts the blocking task on a background thread. Does not wait for the // task to start. void StartBlockingTaskAsync(); // Starts the blocking task on a background thread. Does not return until // the task has been started. void StartBlockingTaskAndWaitForItToStart(); // Cancels the blocking task. void CancelBlocking(); // Verifies that the background task was canceled early. // // This method may block for a brief period of time while waiting for the // background thread to make progress. bool VerifyTaskNotStarted(); private: base::MessageLoop main_loop_; CancelationSignal signal_; base::WaitableEvent task_start_event_; base::WaitableEvent task_done_event_; BlockingTask blocking_task_; }; CancelationSignalTest::CancelationSignalTest() : task_start_event_(false, false), task_done_event_(false, false), blocking_task_(&signal_) {} CancelationSignalTest::~CancelationSignalTest() {} void CancelationSignalTest::StartBlockingTaskAsync() { blocking_task_.RunAsync(&task_start_event_, &task_done_event_); } void CancelationSignalTest::StartBlockingTaskAndWaitForItToStart() { blocking_task_.RunAsync(&task_start_event_, &task_done_event_); task_start_event_.Wait(); } void CancelationSignalTest::CancelBlocking() { signal_.Signal(); } bool CancelationSignalTest::VerifyTaskNotStarted() { // Wait until BlockingTask::Run() has finished. task_done_event_.Wait(); // Verify the background thread never started blocking. return !blocking_task_.WasStarted(); } class FakeCancelationObserver : public CancelationObserver { virtual void OnSignalReceived() OVERRIDE { } }; TEST(CancelationSignalTest_SingleThread, CheckFlags) { FakeCancelationObserver observer; CancelationSignal signal; EXPECT_FALSE(signal.IsSignalled()); signal.Signal(); EXPECT_TRUE(signal.IsSignalled()); EXPECT_FALSE(signal.TryRegisterHandler(&observer)); } // Send the cancelation signal before the task is started. This will ensure // that the task will never be "started" (ie. TryRegisterHandler() will fail, // so it will never start blocking on its main WaitableEvent). TEST_F(CancelationSignalTest, CancelEarly) { CancelBlocking(); StartBlockingTaskAsync(); EXPECT_TRUE(VerifyTaskNotStarted()); } // Send the cancelation signal after the task has started running. This tests // the non-early exit code path, where the task is stopped while it is in // progress. TEST_F(CancelationSignalTest, Cancel) { StartBlockingTaskAndWaitForItToStart(); // Wait for the task to finish and let verify it has been started. CancelBlocking(); EXPECT_FALSE(VerifyTaskNotStarted()); } } // namespace syncer <|endoftext|>
<commit_before>#include "Plane.h" #include "Mesh.h" #include "Texture.h" #include "Logger.h" #include "MeshLoader.h" #include "Engine.h" #include <SDL_main.h> #include <iostream> #include <map> #include <random> #include <components/PerspectiveCamera.h> #include "Menu.h" class DocEditor : public Game { public: virtual void init(GLManager *glManager); virtual void update(double delta); }; void DocEditor::update(double delta) { Game::update(delta); } void DocEditor::init(GLManager *glManager) { // loat assets auto normal = std::make_shared<Texture>(Asset("default_normal.jpg")); auto specular = std::make_shared<Texture>(Asset("default_specular.jpg")); auto backgroundMesh = Plane::getMesh(); auto planeEntity = std::make_shared<Entity>(); planeEntity->getTransform().setPosition(glm::vec3(0, -10, 0)); planeEntity->getTransform().setScale(glm::vec3(755, 1, 600)); addToScene(planeEntity); auto cam = std::make_shared<Entity>(); cam->addComponent<PerspectiveCamera>(glm::pi<float>() / 4.0f * 0.96f, getEngine()->getWindow()->getWidth() / (float)getEngine()->getWindow()->getHeight(), 0.01f, 10000.0f); cam->getTransform().setPosition(glm::vec3(0, getEngine()->getWindow()->getWidth(), 0)); cam->getTransform().setScale(glm::vec3(0.8, 0.8, 0.8)); cam->getTransform().setRotation(glm::quat(0, 0, 0.707, 0.707)); cam->addComponent<DirectionalLight>(glm::vec3(1,1,1), 0.5); addToScene(cam); auto primary_camera = cam->getComponent<PerspectiveCamera>(); getEngine()->getGLManager()->setActiveCamera(primary_camera); } int main(int argc, char *argv[]) { DocEditor game; Engine gameEngine(&game,"DocEditor"); gameEngine.start(); return 0; } <commit_msg>removed broken reference to menu<commit_after>#include "Plane.h" #include "Mesh.h" #include "Texture.h" #include "Logger.h" #include "MeshLoader.h" #include "Engine.h" #include <SDL_main.h> #include <iostream> #include <map> #include <random> #include <components/PerspectiveCamera.h> class DocEditor : public Game { public: virtual void init(GLManager *glManager); virtual void update(double delta); }; void DocEditor::update(double delta) { Game::update(delta); } void DocEditor::init(GLManager *glManager) { // loat assets auto normal = std::make_shared<Texture>(Asset("default_normal.jpg")); auto specular = std::make_shared<Texture>(Asset("default_specular.jpg")); auto backgroundMesh = Plane::getMesh(); auto planeEntity = std::make_shared<Entity>(); planeEntity->getTransform().setPosition(glm::vec3(0, -10, 0)); planeEntity->getTransform().setScale(glm::vec3(755, 1, 600)); addToScene(planeEntity); auto cam = std::make_shared<Entity>(); cam->addComponent<PerspectiveCamera>(glm::pi<float>() / 4.0f * 0.96f, getEngine()->getWindow()->getWidth() / (float)getEngine()->getWindow()->getHeight(), 0.01f, 10000.0f); cam->getTransform().setPosition(glm::vec3(0, getEngine()->getWindow()->getWidth(), 0)); cam->getTransform().setScale(glm::vec3(0.8, 0.8, 0.8)); cam->getTransform().setRotation(glm::quat(0, 0, 0.707, 0.707)); cam->addComponent<DirectionalLight>(glm::vec3(1,1,1), 0.5); addToScene(cam); auto primary_camera = cam->getComponent<PerspectiveCamera>(); getEngine()->getGLManager()->setActiveCamera(primary_camera); } int main(int argc, char *argv[]) { DocEditor game; Engine gameEngine(&game,"DocEditor"); gameEngine.start(); return 0; } <|endoftext|>
<commit_before>#ifndef TEST_STRASSEN_MATRIX_MULTIPLICATION_HPP_ #define TEST_STRASSEN_MATRIX_MULTIPLICATION_HPP_ #include <boost/test/unit_test.hpp> #include "types/matrix.hpp" #include "algorithms/math/strassen_matrix_multiplication.hpp" BOOST_AUTO_TEST_CASE(test_smm_empty_matrices) { BOOST_CHECK(Matrix<int>() == StrassenMatrixMultiplication(Matrix<int>(), Matrix<int>())); Matrix<int> matrix(1, 1, 1); BOOST_CHECK(Matrix<int>() == StrassenMatrixMultiplication(matrix, Matrix<int>())); BOOST_CHECK(Matrix<int>() == StrassenMatrixMultiplication(Matrix<int>(), matrix)); } BOOST_AUTO_TEST_CASE(test_smm_matrices_with_wrong_dimensions) { BOOST_CHECK(Matrix<int>() == StrassenMatrixMultiplication( Matrix<int>(1, 1, 1), Matrix<int>(2, 3, 1))); } BOOST_AUTO_TEST_CASE(test_smm_small_matrices) { Matrix<int> left(2, 2, 0); left.setRowValues(0, {1, 2}); left.setRowValues(1, {3, 4}); Matrix<int> right(2, 2, 0); right.setRowValues(0, {5, 6}); right.setRowValues(1, {7, 8}); Matrix<int> expected(2, 2, 0); expected.setRowValues(0, {19, 22}); expected.setRowValues(1, {43, 50}); BOOST_CHECK(expected == StrassenMatrixMultiplication(left, right)); } BOOST_AUTO_TEST_CASE(test_smm_big_matrices) { Matrix<int> left(2, 3, 0); left.setRowValues(0, {3, 8, 1}); left.setRowValues(1, {-2, 5, 1}); Matrix<int> right(3, 4, 0); right.setRowValues(0, {11, 9, 1, 0}); right.setRowValues(1, {2, 0, 3, 15}); right.setRowValues(2, {2, 6, 6, 7}); Matrix<int> expected(2, 4, 0); expected.setRowValues(0, {51, 33, 33, 127}); expected.setRowValues(1, {-10, -12, 19, 82}); BOOST_CHECK(expected == StrassenMatrixMultiplication(left, right)); } #endif /* TEST_STRASSEN_MATRIX_MULTIPLICATION_HPP_ */ <commit_msg>Disable tests of strassen matrix multiplication - it is not done yet<commit_after>#ifndef TEST_STRASSEN_MATRIX_MULTIPLICATION_HPP_ #define TEST_STRASSEN_MATRIX_MULTIPLICATION_HPP_ //#include <boost/test/unit_test.hpp> //#include "types/matrix.hpp" //#include "algorithms/math/strassen_matrix_multiplication.hpp" //BOOST_AUTO_TEST_CASE(test_smm_empty_matrices) //{ // BOOST_CHECK(Matrix<int>() == // StrassenMatrixMultiplication(Matrix<int>(), Matrix<int>())); // Matrix<int> matrix(1, 1, 1); // BOOST_CHECK(Matrix<int>() == // StrassenMatrixMultiplication(matrix, Matrix<int>())); // BOOST_CHECK(Matrix<int>() == // StrassenMatrixMultiplication(Matrix<int>(), matrix)); //} //BOOST_AUTO_TEST_CASE(test_smm_matrices_with_wrong_dimensions) //{ // BOOST_CHECK(Matrix<int>() == StrassenMatrixMultiplication( // Matrix<int>(1, 1, 1), Matrix<int>(2, 3, 1))); //} //BOOST_AUTO_TEST_CASE(test_smm_small_matrices) //{ // Matrix<int> left(2, 2, 0); // left.setRowValues(0, {1, 2}); // left.setRowValues(1, {3, 4}); // Matrix<int> right(2, 2, 0); // right.setRowValues(0, {5, 6}); // right.setRowValues(1, {7, 8}); // Matrix<int> expected(2, 2, 0); // expected.setRowValues(0, {19, 22}); // expected.setRowValues(1, {43, 50}); // BOOST_CHECK(expected == StrassenMatrixMultiplication(left, right)); //} //BOOST_AUTO_TEST_CASE(test_smm_big_matrices) //{ // Matrix<int> left(2, 3, 0); // left.setRowValues(0, {3, 8, 1}); // left.setRowValues(1, {-2, 5, 1}); // Matrix<int> right(3, 4, 0); // right.setRowValues(0, {11, 9, 1, 0}); // right.setRowValues(1, {2, 0, 3, 15}); // right.setRowValues(2, {2, 6, 6, 7}); // Matrix<int> expected(2, 4, 0); // expected.setRowValues(0, {51, 33, 33, 127}); // expected.setRowValues(1, {-10, -12, 19, 82}); // BOOST_CHECK(expected == StrassenMatrixMultiplication(left, right)); //} #endif /* TEST_STRASSEN_MATRIX_MULTIPLICATION_HPP_ */ <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECore/MessageHandler.h" #include "IECoreAlembic/ObjectAlgo.h" #include "IECoreAlembic/CurvesAlgo.h" #include "IECoreAlembic/GeomBaseAlgo.h" using namespace IECore; using namespace IECoreAlembic; using namespace Alembic::AbcGeom; namespace IECoreAlembic { namespace CurvesAlgo { IECOREALEMBIC_API IECore::CurvesPrimitivePtr convert( const Alembic::AbcGeom::ICurves &curves, const Alembic::Abc::ISampleSelector &sampleSelector ) { const ICurvesSchema curvesSchema = curves.getSchema(); const ICurvesSchema::Sample sample = curvesSchema.getValue( sampleSelector ); IntVectorDataPtr vertsPerCurve = new IntVectorData; vertsPerCurve->writable().insert( vertsPerCurve->writable().end(), sample.getCurvesNumVertices()->get(), sample.getCurvesNumVertices()->get() + sample.getCurvesNumVertices()->size() ); CubicBasisf basis = CubicBasisf::linear(); switch( sample.getType() ) { case kLinear : basis = CubicBasisf::linear(); break; case kCubic : switch( sample.getBasis() ) { case kNoBasis : basis = CubicBasisf::linear(); break; case kBezierBasis : basis = CubicBasisf::bezier(); break; case kCatmullromBasis : basis = CubicBasisf::catmullRom(); break; case kBsplineBasis : basis = CubicBasisf::bSpline(); break; case kHermiteBasis : case kPowerBasis : IECore::msg( IECore::Msg::Warning, "CurvesAlgo::convert", "Unsupported basis" ); basis = CubicBasisf::bSpline(); break; } break; default : basis = CubicBasisf::bSpline(); break; } V3fVectorDataPtr points = new V3fVectorData(); points->writable().resize( sample.getPositions()->size() ); memcpy( &(points->writable()[0]), sample.getPositions()->get(), sample.getPositions()->size() * sizeof( Imath::V3f ) ); CurvesPrimitivePtr result = new CurvesPrimitive( vertsPerCurve, basis, sample.getWrap() == kPeriodic, points ); ICompoundProperty arbGeomParams = curvesSchema.getArbGeomParams(); GeomBaseAlgo::convertArbGeomParams( arbGeomParams, sampleSelector, result.get() ); return result; } } // namespace CurvesAlgo } // namespace IECoreAlembic static ObjectAlgo::ConverterDescription<ICurves, CurvesPrimitive> g_Description( &IECoreAlembic::CurvesAlgo::convert ); <commit_msg>CurvesAlgo : Move basis conversion into anonymous function<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECore/MessageHandler.h" #include "IECoreAlembic/ObjectAlgo.h" #include "IECoreAlembic/CurvesAlgo.h" #include "IECoreAlembic/GeomBaseAlgo.h" using namespace IECore; using namespace IECoreAlembic; using namespace Alembic::AbcGeom; namespace { CubicBasisf convertBasis( const ICurvesSchema::Sample &sample ) { switch( sample.getType() ) { case kLinear : return CubicBasisf::linear(); case kCubic : switch( sample.getBasis() ) { case kNoBasis : return CubicBasisf::linear(); case kBezierBasis : return CubicBasisf::bezier(); case kCatmullromBasis : return CubicBasisf::catmullRom(); case kBsplineBasis : return CubicBasisf::bSpline(); case kHermiteBasis : case kPowerBasis : IECore::msg( IECore::Msg::Warning, "CurvesAlgo::convert", "Unsupported basis" ); return CubicBasisf::bSpline(); } default : return CubicBasisf::bSpline(); } } } // namespace namespace IECoreAlembic { namespace CurvesAlgo { IECOREALEMBIC_API IECore::CurvesPrimitivePtr convert( const Alembic::AbcGeom::ICurves &curves, const Alembic::Abc::ISampleSelector &sampleSelector ) { const ICurvesSchema curvesSchema = curves.getSchema(); const ICurvesSchema::Sample sample = curvesSchema.getValue( sampleSelector ); IntVectorDataPtr vertsPerCurve = new IntVectorData; vertsPerCurve->writable().insert( vertsPerCurve->writable().end(), sample.getCurvesNumVertices()->get(), sample.getCurvesNumVertices()->get() + sample.getCurvesNumVertices()->size() ); V3fVectorDataPtr points = new V3fVectorData(); points->writable().resize( sample.getPositions()->size() ); memcpy( &(points->writable()[0]), sample.getPositions()->get(), sample.getPositions()->size() * sizeof( Imath::V3f ) ); CurvesPrimitivePtr result = new CurvesPrimitive( vertsPerCurve, convertBasis( sample ), sample.getWrap() == kPeriodic, points ); ICompoundProperty arbGeomParams = curvesSchema.getArbGeomParams(); GeomBaseAlgo::convertArbGeomParams( arbGeomParams, sampleSelector, result.get() ); return result; } } // namespace CurvesAlgo } // namespace IECoreAlembic static ObjectAlgo::ConverterDescription<ICurves, CurvesPrimitive> g_Description( &IECoreAlembic::CurvesAlgo::convert ); <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: wrap_ITKBasicFilters.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifdef CABLE_CONFIGURATION #include "itkCSwigMacros.h" namespace _cable_ { const char* const package = ITK_WRAP_PACKAGE_NAME(ITK_WRAP_PACKAGE); const char* const groups[] = { ITK_WRAP_GROUP(itkAnisotropicDiffusionImageFilter), ITK_WRAP_GROUP(itkBinaryThresholdImageFilter), ITK_WRAP_GROUP(itkCannyEdgeDetectionImageFilter), ITK_WRAP_GROUP(itkCastImageFilter), ITK_WRAP_GROUP(itkChangeInformationImageFilter), ITK_WRAP_GROUP(itkConfidenceConnectedImageFilter), ITK_WRAP_GROUP(itkConnectedThresholdImageFilter), ITK_WRAP_GROUP(itkCurvatureAnisotropicDiffusionImageFilter), ITK_WRAP_GROUP(itkCurvatureFlowImageFilter), ITK_WRAP_GROUP(itkDanielssonDistanceMapImageFilter), ITK_WRAP_GROUP(itkExpImageFilter), ITK_WRAP_GROUP(itkExpNegativeImageFilter), ITK_WRAP_GROUP(itkExtractImageFilter), ITK_WRAP_GROUP(itkFastMarchingImageFilter), ITK_WRAP_GROUP(itkFlipImageFilter), ITK_WRAP_GROUP(itkGradientAnisotropicDiffusionImageFilter), ITK_WRAP_GROUP(itkGradientRecursiveGaussianImageFilter), ITK_WRAP_GROUP(itkGradientMagnitudeRecursiveGaussianImageFilter), ITK_WRAP_GROUP(itkGradientMagnitudeImageFilter), ITK_WRAP_GROUP(itkIsolatedConnectedImageFilter), ITK_WRAP_GROUP(itkLaplacianImageFilter), ITK_WRAP_GROUP(itkMeanImageFilter), ITK_WRAP_GROUP(itkMedianImageFilter), ITK_WRAP_GROUP(itkMinimumMaximumImageCalculator), ITK_WRAP_GROUP(itkMinMaxCurvatureFlowImageFilter), ITK_WRAP_GROUP(itkNaryAddImageFilter), ITK_WRAP_GROUP(itkNeighborhoodConnectedImageFilter), ITK_WRAP_GROUP(itkNormalizeImageFilter), ITK_WRAP_GROUP(itkPermuteAxesImageFilter), ITK_WRAP_GROUP(itkRandomImageSource), ITK_WRAP_GROUP(itkRecursiveGaussianImageFilter), ITK_WRAP_GROUP(itkRecursiveSeparableImageFilter), ITK_WRAP_GROUP(itkResampleImageFilter), ITK_WRAP_GROUP(itkRescaleIntensityImageFilter), ITK_WRAP_GROUP(itkShiftScaleImageFilter), ITK_WRAP_GROUP(itkSigmoidImageFilter), ITK_WRAP_GROUP(itkStatisticsImageFilter), ITK_WRAP_GROUP(itkSobelEdgeDetectionImageFilter), ITK_WRAP_GROUP(itkSmoothingRecursiveGaussianImageFilter), ITK_WRAP_GROUP(itkTernaryMagnitudeImageFilter), ITK_WRAP_GROUP(itkThresholdImageFilter), ITK_WRAP_GROUP(itkVTKImageExport), ITK_WRAP_GROUP(itkVTKImageImport) }; } #endif <commit_msg>ERR: Removed ITK_WRAP_GROUP statements for itkCurvatureFlowImageFilter and itkMinMaxCurvatureFlowImageFilter. These two belong in Algorithms.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: wrap_ITKBasicFilters.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifdef CABLE_CONFIGURATION #include "itkCSwigMacros.h" namespace _cable_ { const char* const package = ITK_WRAP_PACKAGE_NAME(ITK_WRAP_PACKAGE); const char* const groups[] = { ITK_WRAP_GROUP(itkAnisotropicDiffusionImageFilter), ITK_WRAP_GROUP(itkBinaryThresholdImageFilter), ITK_WRAP_GROUP(itkCannyEdgeDetectionImageFilter), ITK_WRAP_GROUP(itkCastImageFilter), ITK_WRAP_GROUP(itkChangeInformationImageFilter), ITK_WRAP_GROUP(itkConfidenceConnectedImageFilter), ITK_WRAP_GROUP(itkConnectedThresholdImageFilter), ITK_WRAP_GROUP(itkCurvatureAnisotropicDiffusionImageFilter), ITK_WRAP_GROUP(itkDanielssonDistanceMapImageFilter), ITK_WRAP_GROUP(itkExpImageFilter), ITK_WRAP_GROUP(itkExpNegativeImageFilter), ITK_WRAP_GROUP(itkExtractImageFilter), ITK_WRAP_GROUP(itkFastMarchingImageFilter), ITK_WRAP_GROUP(itkFlipImageFilter), ITK_WRAP_GROUP(itkGradientAnisotropicDiffusionImageFilter), ITK_WRAP_GROUP(itkGradientRecursiveGaussianImageFilter), ITK_WRAP_GROUP(itkGradientMagnitudeRecursiveGaussianImageFilter), ITK_WRAP_GROUP(itkGradientMagnitudeImageFilter), ITK_WRAP_GROUP(itkIsolatedConnectedImageFilter), ITK_WRAP_GROUP(itkLaplacianImageFilter), ITK_WRAP_GROUP(itkMeanImageFilter), ITK_WRAP_GROUP(itkMedianImageFilter), ITK_WRAP_GROUP(itkMinimumMaximumImageCalculator), ITK_WRAP_GROUP(itkNaryAddImageFilter), ITK_WRAP_GROUP(itkNeighborhoodConnectedImageFilter), ITK_WRAP_GROUP(itkNormalizeImageFilter), ITK_WRAP_GROUP(itkPermuteAxesImageFilter), ITK_WRAP_GROUP(itkRandomImageSource), ITK_WRAP_GROUP(itkRecursiveGaussianImageFilter), ITK_WRAP_GROUP(itkRecursiveSeparableImageFilter), ITK_WRAP_GROUP(itkResampleImageFilter), ITK_WRAP_GROUP(itkRescaleIntensityImageFilter), ITK_WRAP_GROUP(itkShiftScaleImageFilter), ITK_WRAP_GROUP(itkSigmoidImageFilter), ITK_WRAP_GROUP(itkStatisticsImageFilter), ITK_WRAP_GROUP(itkSobelEdgeDetectionImageFilter), ITK_WRAP_GROUP(itkSmoothingRecursiveGaussianImageFilter), ITK_WRAP_GROUP(itkTernaryMagnitudeImageFilter), ITK_WRAP_GROUP(itkThresholdImageFilter), ITK_WRAP_GROUP(itkVTKImageExport), ITK_WRAP_GROUP(itkVTKImageImport) }; } #endif <|endoftext|>
<commit_before>/* ** Copyright 2011 Merethis ** ** This file is part of Centreon Clib. ** ** Centreon Clib is free software: you can redistribute it ** and/or modify it under the terms of the GNU Affero General Public ** License as published by the Free Software Foundation, either version ** 3 of the License, or (at your option) any later version. ** ** Centreon Clib 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 ** Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public ** License along with Centreon Clib. If not, see ** <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <assert.h> #include <string.h> #include <assert.h> #include <errno.h> #include <time.h> #include "com/centreon/exception/basic.hh" #include "com/centreon/concurrency/locker.hh" #include "com/centreon/concurrency/thread.hh" using namespace com::centreon::concurrency; /** * Default constructor. */ thread::thread() { } /** * Default destructor. */ thread::~thread() throw () { } /** * Execute the running method in the new thread. */ void thread::exec() { int ret(pthread_create(&_th, NULL, &_execute, this)); if (ret) throw (basic_error() << "failed to create thread:" << strerror(ret)); } /** * Get the current thread id. * * @return The current thread id. */ thread_id thread::get_current_id() throw () { return (pthread_self()); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] msecs Time to sleep in milliseconds. */ void thread::msleep(unsigned long msecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. time_t sec(msecs / 1000); msecs -= sec * 1000; ts.tv_sec += sec; ts.tv_nsec += msecs * 1000 * 1000; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] nsecs Time to sleep in nanoseconds. */ void thread::nsleep(unsigned long nsecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. ts.tv_nsec += nsecs; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] secs Time to sleep in seconds. */ void thread::sleep(unsigned long secs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. ts.tv_sec += secs; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] usecs Time to sleep in micoseconds. */ void thread::usleep(unsigned long usecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. time_t sec(usecs / (1000 * 1000)); usecs -= sec * (1000 * 1000); ts.tv_sec += sec; ts.tv_nsec += usecs * 1000; // Sleep the calling thread. _sleep(&ts); } /** * Wait the end of the thread. */ void thread::wait() { locker lock(&_mtx); // Wait the end of the thread. int ret(pthread_join(_th, NULL)); if (ret && ret != ESRCH) throw (basic_error() << "failed to wait thread:" << strerror(ret)); } /** * This is an overload of wait. * * @param[in] timeout Define the timeout to wait the end of * the thread. * * @return True if the thread end before timeout, otherwise false. */ bool thread::wait(unsigned long timeout) { locker lock(&_mtx); // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed to wait thread:" << strerror(errno)); // Add timeout. time_t sec(timeout / 1000); timeout -= sec * 1000; ts.tv_sec += sec; ts.tv_nsec += timeout * 1000 * 1000; // Wait the end of the thread or timeout. int ret(pthread_timedjoin_np(_th, NULL, &ts)); if (!ret || ret == ESRCH) return (true); if (ret == ETIMEDOUT) return (false); throw (basic_error() << "failed to wait thread:" << strerror(ret)); } /** * Causes the calling thread to relinquish the CPU. * @remark This function is static. */ void thread::yield() throw () { sched_yield(); } /** * Default copy constructor. * * @param[in] right The object to copy. */ thread::thread(thread const& right) { _internal_copy(right); } /** * Default copy operator. * * @param[in] right The object to copy. * * @return This object. */ thread& thread::operator=(thread const& right) { return (_internal_copy(right)); } /** * The thread start routine. * @remark This function is static. * * @param[in] data This thread object. * * @return always return zero. */ void* thread::_execute(void* data) { thread* self(static_cast<thread*>(data)); if (self) self->_run(); return (0); } /** * Internal copy. * * @param[in] right The object to copy. * * @return This object. */ thread& thread::_internal_copy(thread const& right) { (void)right; assert(!"impossible to copy thread"); abort(); return (*this); } /** * Internal sleep, Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] ts Time to sleep with timespec struct. */ void thread::_sleep(timespec* ts) { int ret(0); // Create mutex. pthread_mutex_t mtx; pthread_mutex_init(&mtx, NULL); // Create condition variable. pthread_cond_t cnd; pthread_cond_init(&cnd, NULL); // Lock the mutex. if ((ret = pthread_mutex_lock(&mtx))) throw (basic_error() << "impossible to sleep:" << strerror(ret)); // Wait the timeout of the condition variable. if ((ret = pthread_cond_timedwait(&cnd, &mtx, ts)) && ret != ETIMEDOUT) throw (basic_error() << "impossible to sleep:" << strerror(ret)); // Release mutex. if ((ret = pthread_mutex_unlock(&mtx))) throw (basic_error() << "impossible in sleep:" << strerror(ret)); // Cleanup. pthread_cond_destroy(&cnd); pthread_mutex_destroy(&mtx); } <commit_msg>Fix overflow into thread::wait and add ifdef for used pthread_tryjoin[_np].<commit_after>/* ** Copyright 2011 Merethis ** ** This file is part of Centreon Clib. ** ** Centreon Clib is free software: you can redistribute it ** and/or modify it under the terms of the GNU Affero General Public ** License as published by the Free Software Foundation, either version ** 3 of the License, or (at your option) any later version. ** ** Centreon Clib 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 ** Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public ** License along with Centreon Clib. If not, see ** <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <assert.h> #include <string.h> #include <assert.h> #include <errno.h> #include <time.h> #include "com/centreon/exception/basic.hh" #include "com/centreon/concurrency/locker.hh" #include "com/centreon/concurrency/thread.hh" using namespace com::centreon::concurrency; /** * Default constructor. */ thread::thread() { } /** * Default destructor. */ thread::~thread() throw () { } /** * Execute the running method in the new thread. */ void thread::exec() { int ret(pthread_create(&_th, NULL, &_execute, this)); if (ret) throw (basic_error() << "failed to create thread:" << strerror(ret)); } /** * Get the current thread id. * * @return The current thread id. */ thread_id thread::get_current_id() throw () { return (pthread_self()); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] msecs Time to sleep in milliseconds. */ void thread::msleep(unsigned long msecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. time_t sec(msecs / 1000); msecs -= sec * 1000; ts.tv_sec += sec; ts.tv_nsec += msecs * 1000 * 1000; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] nsecs Time to sleep in nanoseconds. */ void thread::nsleep(unsigned long nsecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. ts.tv_nsec += nsecs; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] secs Time to sleep in seconds. */ void thread::sleep(unsigned long secs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. ts.tv_sec += secs; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] usecs Time to sleep in micoseconds. */ void thread::usleep(unsigned long usecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. time_t sec(usecs / (1000 * 1000)); usecs -= sec * (1000 * 1000); ts.tv_sec += sec; ts.tv_nsec += usecs * 1000; // Sleep the calling thread. _sleep(&ts); } /** * Wait the end of the thread. */ void thread::wait() { locker lock(&_mtx); // Wait the end of the thread. int ret(pthread_join(_th, NULL)); if (ret && ret != ESRCH) throw (basic_error() << "failed to wait thread:" << strerror(ret)); } /** * This is an overload of wait. * * @param[in] timeout Define the timeout to wait the end of * the thread. * * @return True if the thread end before timeout, otherwise false. */ bool thread::wait(unsigned long timeout) { locker lock(&_mtx); // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed to wait thread:" << strerror(errno)); // Transforms unnecessary microseconds into seconds. time_t sec(ts.tv_nsec / 1000000); ts.tv_nsec -= sec * 1000000; ts.tv_sec += sec; // Add timeout. sec = timeout / 1000; timeout -= sec * 1000; ts.tv_sec += sec; ts.tv_nsec += timeout * 1000000; // Wait the end of the thread or timeout. #ifdef __linux__ int ret(pthread_timedjoin_np(_th, NULL, &ts)); #else int ret(pthread_timedjoin(_th, NULL, &ts)); #endif // __linux__ if (!ret || ret == ESRCH) return (true); if (ret == ETIMEDOUT) return (false); throw (basic_error() << "failed to wait thread:" << strerror(ret)); } /** * Causes the calling thread to relinquish the CPU. * @remark This function is static. */ void thread::yield() throw () { sched_yield(); } /** * Default copy constructor. * * @param[in] right The object to copy. */ thread::thread(thread const& right) { _internal_copy(right); } /** * Default copy operator. * * @param[in] right The object to copy. * * @return This object. */ thread& thread::operator=(thread const& right) { return (_internal_copy(right)); } /** * The thread start routine. * @remark This function is static. * * @param[in] data This thread object. * * @return always return zero. */ void* thread::_execute(void* data) { thread* self(static_cast<thread*>(data)); if (self) self->_run(); return (0); } /** * Internal copy. * * @param[in] right The object to copy. * * @return This object. */ thread& thread::_internal_copy(thread const& right) { (void)right; assert(!"impossible to copy thread"); abort(); return (*this); } /** * Internal sleep, Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] ts Time to sleep with timespec struct. */ void thread::_sleep(timespec* ts) { int ret(0); // Create mutex. pthread_mutex_t mtx; pthread_mutex_init(&mtx, NULL); // Create condition variable. pthread_cond_t cnd; pthread_cond_init(&cnd, NULL); // Lock the mutex. if ((ret = pthread_mutex_lock(&mtx))) throw (basic_error() << "impossible to sleep:" << strerror(ret)); // Wait the timeout of the condition variable. if ((ret = pthread_cond_timedwait(&cnd, &mtx, ts)) && ret != ETIMEDOUT) throw (basic_error() << "impossible to sleep:" << strerror(ret)); // Release mutex. if ((ret = pthread_mutex_unlock(&mtx))) throw (basic_error() << "impossible in sleep:" << strerror(ret)); // Cleanup. pthread_cond_destroy(&cnd); pthread_mutex_destroy(&mtx); } <|endoftext|>
<commit_before>/* ** Copyright 1986, 1987, 1988, 1989, 1990, 1991 by the Condor Design Team ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, ** provided that the above copyright notice appear in all copies and that ** both that copyright notice and this permission notice appear in ** supporting documentation, and that the names of the University of ** Wisconsin and the Condor Design Team not be used in advertising or ** publicity pertaining to distribution of the software without specific, ** written prior permission. The University of Wisconsin and the Condor ** Design Team make no representations about the suitability of this ** software for any purpose. It is provided "as is" without express ** or implied warranty. ** ** THE UNIVERSITY OF WISCONSIN AND THE CONDOR DESIGN TEAM DISCLAIM ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF ** WISCONSIN OR THE CONDOR DESIGN TEAM BE LIABLE FOR ANY SPECIAL, INDIRECT ** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS ** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE ** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ** OR PERFORMANCE OF THIS SOFTWARE. ** ** Authors: Allan Bricker and Michael J. Litzkow, ** University of Wisconsin, Computer Sciences Dept. ** */ /********************************************************************* * Ask a machine which has been hosting a condor job to kick it off as * though the machine had become busy with non-condor work. Used * for debugging... *********************************************************************/ #include "condor_common.h" #include "condor_config.h" #include "condor_debug.h" #include "condor_io.h" static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */ extern "C" char *get_startd_addr(const char *); usage( char *str ) { fprintf( stderr, "Usage: %s hostname-list\n", str ); exit( 1 ); } main( int argc, char *argv[] ) { int cmd; int i; char *startdAddr; if( argc < 2 ) { usage( argv[0] ); } config( 0 ); #if !defined(WIN32) install_sig_handler(SIGPIPE, SIG_IGN ); #endif if ((startdAddr = get_startd_addr(argv[1])) == NULL) { EXCEPT("Can't find startd address on %s\n", argv[1]); } for (i = 1; i < argc; i++) { /* Connect to the specified host */ ReliSock sock(startdAddr, START_PORT); if(sock.get_file_desc() < 0) { dprintf( D_ALWAYS, "Can't connect to condor startd (%s)\n", startdAddr ); continue; } sock.encode(); cmd = VACATE_ALL_CLAIMS; if (!sock.code(cmd) || !sock.eom()) { dprintf(D_ALWAYS, "Can't send VACATE_ALL_CLAIMS command to " "condor startd (%s)\n", startdAddr); continue; } printf( "Sent VACATE_ALL_CLAIMS command to startd on %s\n", argv[i] ); } exit( 0 ); } extern "C" SetSyscalls(){} <commit_msg>+ We now actually try to connect to all the hosts we're given on the command line, instead of sending the command to the same startd over and over again. *grin* + We no longer use EXCEPT and dprintf, since they give us more than we want. Error messages now just go straight to stderr. + We don't EXCEPT (or exit) when we can't find a startd addr, we just go onto the next host we were given. + Our error messages distinguish between not being able to resolve a given hostname and the CM not having the startd ad for that host.<commit_after>/* ** Copyright 1986, 1987, 1988, 1989, 1990, 1991 by the Condor Design Team ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, ** provided that the above copyright notice appear in all copies and that ** both that copyright notice and this permission notice appear in ** supporting documentation, and that the names of the University of ** Wisconsin and the Condor Design Team not be used in advertising or ** publicity pertaining to distribution of the software without specific, ** written prior permission. The University of Wisconsin and the Condor ** Design Team make no representations about the suitability of this ** software for any purpose. It is provided "as is" without express ** or implied warranty. ** ** THE UNIVERSITY OF WISCONSIN AND THE CONDOR DESIGN TEAM DISCLAIM ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF ** WISCONSIN OR THE CONDOR DESIGN TEAM BE LIABLE FOR ANY SPECIAL, INDIRECT ** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS ** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE ** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ** OR PERFORMANCE OF THIS SOFTWARE. ** ** Authors: Allan Bricker and Michael J. Litzkow, ** University of Wisconsin, Computer Sciences Dept. ** */ /********************************************************************* * Ask a machine which has been hosting a condor job to kick it off as * though the machine had become busy with non-condor work. Used * for debugging... *********************************************************************/ #include "condor_common.h" #include "condor_config.h" #include "condor_io.h" #include "get_full_hostname.h" extern "C" char *get_startd_addr(const char *); usage( char *str ) { fprintf( stderr, "Usage: %s hostname-list\n", str ); exit( 1 ); } main( int argc, char *argv[] ) { int cmd; int i; char *startdAddr; char *fullname; if( argc < 2 ) { usage( argv[0] ); } config( 0 ); #if !defined(WIN32) install_sig_handler(SIGPIPE, SIG_IGN ); #endif for (i = 1; i < argc; i++) { if( (fullname = get_full_hostname(argv[i])) == NULL ) { fprintf( stderr, "%s: unknown host %s\n", argv[0], argv[i] ); continue; } if( (startdAddr = get_startd_addr(fullname)) == NULL ) { fprintf( stderr, "%s: can't find address of startd on %s\n", argv[0], argv[i] ); continue; } /* Connect to the specified host */ ReliSock sock(startdAddr, START_PORT); if(sock.get_file_desc() < 0) { fprintf( stderr, "Can't connect to condor startd (%s)\n", startdAddr ); continue; } sock.encode(); cmd = VACATE_ALL_CLAIMS; if (!sock.code(cmd) || !sock.eom()) { fprintf( stderr, "Can't send VACATE_ALL_CLAIMS command to " "condor startd (%s)\n", startdAddr); continue; } printf( "Sent VACATE_ALL_CLAIMS command to startd on %s\n", argv[i] ); } exit( 0 ); } extern "C" SetSyscalls(){} <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(FACTORY_HEADER_GUARD_1357924680) #define FACTORY_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <PlatformSupport/PlatformSupportDefinitions.hpp> #include <cassert> #include <functional> #include <PlatformSupport/Resettable.hpp> class FactoryObject; class XALAN_PLATFORMSUPPORT_EXPORT Factory : public Resettable { public: explicit Factory(); virtual ~Factory(); // These interfaces are inherited from Resetable... /** * Reset the instance. This invalidates all existing FactoryObject * instances created with this Factory. */ virtual void reset() = 0; // These interfaces are new... /** * Return an object to the factory. * * @param theFactoryObject object to be returned */ bool returnObject(const FactoryObject* theFactoryObject) { return doReturnObject(theFactoryObject); } protected: /** * Delete a FactoryObject instance. */ virtual bool deleteObject(const FactoryObject* theFactoryObject) const; /** * Return an object to the factory. * * @param theFactoryObject object to be returned * @param fInReset true when called during reset(). */ virtual bool doReturnObject( const FactoryObject* theFactoryObject, bool fInReset = false) = 0; /** * * A functor for use with stl algorithms. * */ #if defined(XALAN_NO_NAMESPACES) struct DeleteFactoryObjectFunctor : public unary_function<const FactoryObject*, void> #else struct DeleteFactoryObjectFunctor : public std::unary_function<const FactoryObject*, void> #endif { public: DeleteFactoryObjectFunctor( Factory& theFactoryInstance, bool fInReset = false) : m_factoryInstance(theFactoryInstance), m_fInReset(fInReset) { } result_type operator()(argument_type theFactoryObject) const { m_factoryInstance.doReturnObject(theFactoryObject, m_fInReset); } private: Factory& m_factoryInstance; const bool m_fInReset; }; friend struct DeleteFactoryObjectFunctor; private: // Not implemented... Factory(const Factory&); Factory& operator=(const Factory&); bool operator==(const Factory&) const; }; // auto_ptr-like class for FactoryObject instances (and it's derivatives). template<class Type> class FactoryObjectAutoPointer { public: // Construct a FactoryObjectAutoPointer. Either both parameters should // be valid or pointers or they should both be 0. explicit FactoryObjectAutoPointer( Factory* theFactory = 0, Type* theObject = 0) : m_factory(theFactory), m_object(theObject) { assert(theFactory != 0 && theObject != 0 || theFactory == 0 && theObject == 0); } // Note that copy construction is not const for the source object. Once // copied, the source object will no longer refer to a valid object! #if defined(XALAN_MEMBER_TEMPLATES) template <class CompatibleType> FactoryObjectAutoPointer(FactoryObjectAutoPointer<CompatibleType>& theRHS) #else FactoryObjectAutoPointer(FactoryObjectAutoPointer<Type>& theRHS) #endif { adopt(theRHS); } ~FactoryObjectAutoPointer() { returnObject(); } Type* operator->() const { return m_object; } Type* get() const { return m_object; } void reset(Factory* theFactory = 0, Type* theObject = 0) { assert(theFactory != 0 && theObject != 0 || theFactory == 0 && theObject == 0); returnObject(); m_factory = theFactory; m_object = theObject; } Type* release() { Type* const theTemp = m_object; m_object = 0; m_factory = 0; return theTemp; } bool returnObject() { bool fReturn = false; if (m_object != 0) { assert(m_factory != 0); fReturn = m_factory->returnObject(m_object); } m_object = 0; m_factory = 0; return fReturn; } // Note that assignment is not const for the source object. Once // copied, the source object will no longer refer to a valid object! #if defined(XALAN_MEMBER_TEMPLATES) template <class CompatibleType> FactoryObjectAutoPointer& operator=(FactoryObjectAutoPointer<CompatibleType& theRHS) #else FactoryObjectAutoPointer& operator=(FactoryObjectAutoPointer<Type>& theRHS) #endif { if (static_cast<void*>(this) != static_cast<void*>(&theRHS)) { adopt(theRHS); } return *this; } #if defined(XALAN_MEMBER_TEMPLATES) template <class CompatibleType> bool operator==(const FactoryObjectAutoPointer<CompatibleType& theRHS) const #else bool operator==(const FactoryObjectAutoPointer&) const #endif { return m_object == theRHS.m_object ? true : false; } private: #if defined(XALAN_MEMBER_TEMPLATES) template <class CompatibleType> void adopt(FactoryObjectAutoPointer<CompatibleType& theRHS) #else void adopt(FactoryObjectAutoPointer<Type>& theRHS) #endif { if (m_object != theRHS.m_object) { // Return the object we're now pointing // to. returnObject(); } // Adopt the object and factory of the source // object. m_factory = theRHS.m_factory; m_object = theRHS.m_object; // The source object will no longer refer // to the object. theRHS.m_object = 0; theRHS.m_factory = 0; } // Data members... Factory* m_factory; Type* m_object; }; #endif // FACTORY_HEADER_GUARD_1357924680 <commit_msg>Made a public version of the delete functor and changed the name of the protected one.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(FACTORY_HEADER_GUARD_1357924680) #define FACTORY_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <PlatformSupport/PlatformSupportDefinitions.hpp> #include <cassert> #include <functional> #include <PlatformSupport/Resettable.hpp> class FactoryObject; class XALAN_PLATFORMSUPPORT_EXPORT Factory : public Resettable { public: explicit Factory(); virtual ~Factory(); // These interfaces are inherited from Resetable... /** * Reset the instance. This invalidates all existing FactoryObject * instances created with this Factory. */ virtual void reset() = 0; // These interfaces are new... /** * Return an object to the factory. * * @param theFactoryObject object to be returned */ bool returnObject(const FactoryObject* theFactoryObject) { return doReturnObject(theFactoryObject); } protected: /** * Delete a FactoryObject instance. */ virtual bool deleteObject(const FactoryObject* theFactoryObject) const; /** * Return an object to the factory. * * @param theFactoryObject object to be returned * @param fInReset true when called during reset(). */ virtual bool doReturnObject( const FactoryObject* theFactoryObject, bool fInReset = false) = 0; /** * * A functor for use with stl algorithms. * */ #if defined(XALAN_NO_NAMESPACES) struct ProtectedDeleteFactoryObjectFunctor : public unary_function<const FactoryObject*, void> #else struct ProtectedDeleteFactoryObjectFunctor : public std::unary_function<const FactoryObject*, void> #endif { public: ProtectedDeleteFactoryObjectFunctor( Factory& theFactoryInstance, bool fInReset) : m_factoryInstance(theFactoryInstance), m_fInReset(fInReset) { } result_type operator()(argument_type theFactoryObject) const { m_factoryInstance.doReturnObject(theFactoryObject, m_fInReset); } private: Factory& m_factoryInstance; const bool m_fInReset; }; friend struct ProtectedDeleteFactoryObjectFunctor; private: // Not implemented... Factory(const Factory&); Factory& operator=(const Factory&); bool operator==(const Factory&) const; }; // auto_ptr-like class for FactoryObject instances (and it's derivatives). template<class Type> class FactoryObjectAutoPointer { public: // Construct a FactoryObjectAutoPointer. Either both parameters should // be valid or pointers or they should both be 0. explicit FactoryObjectAutoPointer( Factory* theFactory = 0, Type* theObject = 0) : m_factory(theFactory), m_object(theObject) { assert(theFactory != 0 && theObject != 0 || theFactory == 0 && theObject == 0); } // Note that copy construction is not const for the source object. Once // copied, the source object will no longer refer to a valid object! #if defined(XALAN_MEMBER_TEMPLATES) template <class CompatibleType> FactoryObjectAutoPointer(FactoryObjectAutoPointer<CompatibleType>& theRHS) #else FactoryObjectAutoPointer(FactoryObjectAutoPointer<Type>& theRHS) #endif { adopt(theRHS); } ~FactoryObjectAutoPointer() { returnObject(); } Type* operator->() const { return m_object; } Type* get() const { return m_object; } void reset(Factory* theFactory = 0, Type* theObject = 0) { assert(theFactory != 0 && theObject != 0 || theFactory == 0 && theObject == 0); returnObject(); m_factory = theFactory; m_object = theObject; } Type* release() { Type* const theTemp = m_object; m_object = 0; m_factory = 0; return theTemp; } bool returnObject() { bool fReturn = false; if (m_object != 0) { assert(m_factory != 0); fReturn = m_factory->returnObject(m_object); } m_object = 0; m_factory = 0; return fReturn; } // Note that assignment is not const for the source object. Once // copied, the source object will no longer refer to a valid object! #if defined(XALAN_MEMBER_TEMPLATES) template <class CompatibleType> FactoryObjectAutoPointer& operator=(FactoryObjectAutoPointer<CompatibleType& theRHS) #else FactoryObjectAutoPointer& operator=(FactoryObjectAutoPointer<Type>& theRHS) #endif { if (static_cast<void*>(this) != static_cast<void*>(&theRHS)) { adopt(theRHS); } return *this; } #if defined(XALAN_MEMBER_TEMPLATES) template <class CompatibleType> bool operator==(const FactoryObjectAutoPointer<CompatibleType& theRHS) const #else bool operator==(const FactoryObjectAutoPointer&) const #endif { return m_object == theRHS.m_object ? true : false; } private: #if defined(XALAN_MEMBER_TEMPLATES) template <class CompatibleType> void adopt(FactoryObjectAutoPointer<CompatibleType& theRHS) #else void adopt(FactoryObjectAutoPointer<Type>& theRHS) #endif { if (m_object != theRHS.m_object) { // Return the object we're now pointing // to. returnObject(); } // Adopt the object and factory of the source // object. m_factory = theRHS.m_factory; m_object = theRHS.m_object; // The source object will no longer refer // to the object. theRHS.m_object = 0; theRHS.m_factory = 0; } // Data members... Factory* m_factory; Type* m_object; }; /** * * A public functor for use with stl algorithms. * */ #if defined(XALAN_NO_NAMESPACES) struct DeleteFactoryObjectFunctor : public unary_function<const FactoryObject*, void> #else struct DeleteFactoryObjectFunctor : public std::unary_function<const FactoryObject*, void> #endif { public: DeleteFactoryObjectFunctor(Factory& theFactoryInstance) : m_factoryInstance(theFactoryInstance) { } result_type operator()(argument_type theFactoryObject) const { m_factoryInstance.returnObject(theFactoryObject); } private: Factory& m_factoryInstance; }; #endif // FACTORY_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>/* Copyright (C) 2009-2010 George Kiagiadakis <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "caps.h" #include "structure.h" #include "../QGlib/string_p.h" #include "objectstore_p.h" #include <QtCore/QDebug> #include <gst/gstcaps.h> #include <gst/gstvalue.h> namespace QGst { //static CapsPtr Caps::createSimple(const char *mediaType) { return CapsPtr::wrap(gst_caps_new_simple(mediaType, NULL), false); } //static CapsPtr Caps::createAny() { return CapsPtr::wrap(gst_caps_new_any(), false); } //static CapsPtr Caps::createEmpty() { return CapsPtr::wrap(gst_caps_new_empty(), false); } //static CapsPtr Caps::fromString(const char *string) { return CapsPtr::wrap(gst_caps_from_string(string), false); } QString Caps::toString() const { return QGlib::Private::stringFromGCharPtr(gst_caps_to_string(object<GstCaps>())); } void Caps::append(const CapsPtr & caps2) { gst_caps_append(object<GstCaps>(), gst_caps_copy(caps2)); } CapsPtr Caps::merge(CapsPtr & caps2) { return CapsPtr::wrap(gst_caps_merge(object<GstCaps>(), caps2), false); } void Caps::setValue(const char *field, const QGlib::Value & value) { gst_caps_set_value(object<GstCaps>(), field, value); } bool Caps::simplify() { return gst_caps_simplify(object<GstCaps>()); } CapsPtr Caps::truncate() { return CapsPtr::wrap(gst_caps_truncate(object<GstCaps>()), false); } StructurePtr Caps::internalStructure(uint index) { GstStructure *structure = gst_caps_get_structure(object<GstCaps>(), index); return SharedStructure::fromCaps(structure, CapsPtr(this)); } void Caps::appendStructure(const Structure & structure) { gst_caps_append_structure(object<GstCaps>(), gst_structure_copy(structure)); } CapsPtr Caps::mergeStructure(Structure & structure) { return CapsPtr::wrap(gst_caps_merge_structure(object<GstCaps>(), structure), false); } void Caps::removeStructure(uint index) { gst_caps_remove_structure(object<GstCaps>(), index); } uint Caps::size() const { return gst_caps_get_size(object<GstCaps>()); } bool Caps::isSimple() const { return GST_CAPS_IS_SIMPLE(object<GstCaps>()); } bool Caps::isAny() const { return gst_caps_is_any(object<GstCaps>()); } bool Caps::isEmpty() const { return gst_caps_is_empty(object<GstCaps>()); } bool Caps::isFixed() const { return gst_caps_is_fixed(object<GstCaps>()); } bool Caps::isWritable() const { GstCaps *caps = object<GstCaps>(); //workaround for bug #653266 return (GST_CAPS_REFCOUNT_VALUE(caps) == 1); } bool Caps::equals(const CapsPtr & caps2) const { return gst_caps_is_equal(object<GstCaps>(), caps2); } bool Caps::isAlwaysCompatibleWith(const CapsPtr & caps2) const { return gst_caps_is_always_compatible(object<GstCaps>(), caps2); } bool Caps::isSubsetOf(const CapsPtr & superset) const { return gst_caps_is_subset(object<GstCaps>(), superset); } bool Caps::canIntersect(const CapsPtr & caps2) const { return gst_caps_can_intersect(object<GstCaps>(), caps2); } CapsPtr Caps::getIntersection(const CapsPtr & caps2) const { return CapsPtr::wrap(gst_caps_intersect(object<GstCaps>(), caps2), false); } CapsPtr Caps::getNormal() { return CapsPtr::wrap(gst_caps_normalize(object<GstCaps>()), false); } CapsPtr Caps::subtract(const CapsPtr & subtrahend) const { return CapsPtr::wrap(gst_caps_subtract(object<GstCaps>(), subtrahend), false); } CapsPtr Caps::copy() const { return CapsPtr::wrap(gst_caps_copy(object<GstCaps>()), false); } CapsPtr Caps::copyNth(uint index) const { return CapsPtr::wrap(gst_caps_copy_nth(object<GstCaps>(), index), false); } void Caps::ref(bool increaseRef) { if (Private::ObjectStore::put(this)) { if (increaseRef) { gst_caps_ref(GST_CAPS(m_object)); } } } void Caps::unref() { if (Private::ObjectStore::take(this)) { gst_caps_unref(GST_CAPS(m_object)); delete this; } } CapsPtr Caps::makeWritable() const { /* * Calling gst_*_make_writable() below is tempting but wrong. * Since MiniObjects and Caps do not share the same C++ instance in various wrappings, calling * gst_*_make_writable() on an already writable object and wrapping the result is wrong, * since it would just return the same pointer and we would wrap it in a new C++ instance. */ if (!isWritable()) { return copy(); } else { return CapsPtr(const_cast<Caps*>(this)); } } QDebug operator<<(QDebug debug, const CapsPtr & caps) { debug.nospace() << "QGst::Caps(" << caps->toString() << ")"; return debug.space(); } } //namespace QGst <commit_msg>src/QGst/caps.cpp use gst_caps_new_empty_simple<commit_after>/* Copyright (C) 2009-2010 George Kiagiadakis <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "caps.h" #include "structure.h" #include "../QGlib/string_p.h" #include "objectstore_p.h" #include <QtCore/QDebug> #include <gst/gstcaps.h> #include <gst/gstvalue.h> namespace QGst { //static CapsPtr Caps::createSimple(const char *mediaType) { return CapsPtr::wrap(gst_caps_new_empty_simple(mediaType), false); } //static CapsPtr Caps::createAny() { return CapsPtr::wrap(gst_caps_new_any(), false); } //static CapsPtr Caps::createEmpty() { return CapsPtr::wrap(gst_caps_new_empty(), false); } //static CapsPtr Caps::fromString(const char *string) { return CapsPtr::wrap(gst_caps_from_string(string), false); } QString Caps::toString() const { return QGlib::Private::stringFromGCharPtr(gst_caps_to_string(object<GstCaps>())); } void Caps::append(const CapsPtr & caps2) { gst_caps_append(object<GstCaps>(), gst_caps_copy(caps2)); } CapsPtr Caps::merge(CapsPtr & caps2) { return CapsPtr::wrap(gst_caps_merge(object<GstCaps>(), caps2), false); } void Caps::setValue(const char *field, const QGlib::Value & value) { gst_caps_set_value(object<GstCaps>(), field, value); } bool Caps::simplify() { return gst_caps_simplify(object<GstCaps>()); } CapsPtr Caps::truncate() { return CapsPtr::wrap(gst_caps_truncate(object<GstCaps>()), false); } StructurePtr Caps::internalStructure(uint index) { GstStructure *structure = gst_caps_get_structure(object<GstCaps>(), index); return SharedStructure::fromCaps(structure, CapsPtr(this)); } void Caps::appendStructure(const Structure & structure) { gst_caps_append_structure(object<GstCaps>(), gst_structure_copy(structure)); } CapsPtr Caps::mergeStructure(Structure & structure) { return CapsPtr::wrap(gst_caps_merge_structure(object<GstCaps>(), structure), false); } void Caps::removeStructure(uint index) { gst_caps_remove_structure(object<GstCaps>(), index); } uint Caps::size() const { return gst_caps_get_size(object<GstCaps>()); } bool Caps::isSimple() const { return GST_CAPS_IS_SIMPLE(object<GstCaps>()); } bool Caps::isAny() const { return gst_caps_is_any(object<GstCaps>()); } bool Caps::isEmpty() const { return gst_caps_is_empty(object<GstCaps>()); } bool Caps::isFixed() const { return gst_caps_is_fixed(object<GstCaps>()); } bool Caps::isWritable() const { GstCaps *caps = object<GstCaps>(); //workaround for bug #653266 return (GST_CAPS_REFCOUNT_VALUE(caps) == 1); } bool Caps::equals(const CapsPtr & caps2) const { return gst_caps_is_equal(object<GstCaps>(), caps2); } bool Caps::isAlwaysCompatibleWith(const CapsPtr & caps2) const { return gst_caps_is_always_compatible(object<GstCaps>(), caps2); } bool Caps::isSubsetOf(const CapsPtr & superset) const { return gst_caps_is_subset(object<GstCaps>(), superset); } bool Caps::canIntersect(const CapsPtr & caps2) const { return gst_caps_can_intersect(object<GstCaps>(), caps2); } CapsPtr Caps::getIntersection(const CapsPtr & caps2) const { return CapsPtr::wrap(gst_caps_intersect(object<GstCaps>(), caps2), false); } CapsPtr Caps::getNormal() { return CapsPtr::wrap(gst_caps_normalize(object<GstCaps>()), false); } CapsPtr Caps::subtract(const CapsPtr & subtrahend) const { return CapsPtr::wrap(gst_caps_subtract(object<GstCaps>(), subtrahend), false); } CapsPtr Caps::copy() const { return CapsPtr::wrap(gst_caps_copy(object<GstCaps>()), false); } CapsPtr Caps::copyNth(uint index) const { return CapsPtr::wrap(gst_caps_copy_nth(object<GstCaps>(), index), false); } void Caps::ref(bool increaseRef) { if (Private::ObjectStore::put(this)) { if (increaseRef) { gst_caps_ref(GST_CAPS(m_object)); } } } void Caps::unref() { if (Private::ObjectStore::take(this)) { gst_caps_unref(GST_CAPS(m_object)); delete this; } } CapsPtr Caps::makeWritable() const { /* * Calling gst_*_make_writable() below is tempting but wrong. * Since MiniObjects and Caps do not share the same C++ instance in various wrappings, calling * gst_*_make_writable() on an already writable object and wrapping the result is wrong, * since it would just return the same pointer and we would wrap it in a new C++ instance. */ if (!isWritable()) { return copy(); } else { return CapsPtr(const_cast<Caps*>(this)); } } QDebug operator<<(QDebug debug, const CapsPtr & caps) { debug.nospace() << "QGst::Caps(" << caps->toString() << ")"; return debug.space(); } } //namespace QGst <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2016 Rony Shapiro <[email protected]>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ #include <wx/clipbrd.h> #include <wx/dataobj.h> /* NOTE: In VS2013 wxWidgets 3.0.x builds: Both <wx/clipbrd.h> & <wx/dataobj.h> cause 51 warnings about using unsecure versions of standard calls, such as 'wcscpy' instead of 'wcscpy_s', if any previously included header file includes <string> even though pre-processor variables _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES and _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT are defined. The solution is to ensure that any header files containing <string>, e.g. "core/StringX.h", are placed after these two wxWidgets include statements. This issue did not occur with wxWidgets 2.8.12. For this reason, "pwsclip.h", which includes "core/StringX.h" that also includes <string>, is placed here after <wx/clipbrd.h> & <wx/dataobj.h>. */ #include "pwsclip.h" #ifdef __WXMSW__ #include <wx/msw/msvcrt.h> #endif PWSclipboard *PWSclipboard::self = nullptr; /** * Get pointer to single instance of clipboard manager */ PWSclipboard *PWSclipboard::GetInstance() { if (self == nullptr) { self = new PWSclipboard(); } return self; } /** * Destroy the instance */ void PWSclipboard::DeleteInstance() { delete self; self = nullptr; } PWSclipboard::PWSclipboard(): m_set(false) { memset(m_digest, 0, sizeof(m_digest)); } /** * Put text data to clipboard * @param[in] data data to store in clipboard * @param isSensitive if data sensitive, we remeber its hash and will clear on ClearData() call * @return \c true, if we could open the clipboard and put the data */ bool PWSclipboard::SetData(const StringX &data) { wxMutexLocker clip(m_clipboardMutex); bool res = false; if (wxTheClipboard->Open()) { res = wxTheClipboard->SetData(new wxTextDataObject(data.c_str())); wxTheClipboard->Close(); } m_set = true; if (res) { // identify data in clipboard as ours, so as not to clear the wrong data later // of course, we don't want an extra copy of a password floating around // in memory, so we'll use the hash SHA256 ctx; const wchar_t *str = data.c_str(); ctx.Update(reinterpret_cast<const unsigned char *>(str), data.length()*sizeof(wchar_t)); ctx.Final(m_digest); } return res; } /** * Clear from clipboard data, that we put there previously * @return \c true, if we cleared our data, or stored data don't belong to us */ bool PWSclipboard::ClearData() { wxMutexLocker clip(m_clipboardMutex); if (m_set && wxTheClipboard->Open()) { wxTextDataObject obj; if (wxTheClipboard->IsSupported(wxDF_UNICODETEXT) && wxTheClipboard->GetData(obj)) { StringX buf(obj.GetText().data(), obj.GetText().size()); if (buf.length()) { // check if the data on the clipboard is the same we put there unsigned char digest[SHA256::HASHLEN]; SHA256 ctx; ctx.Update(reinterpret_cast<const unsigned char *>(buf.c_str()), buf.length()*sizeof(wchar_t)); ctx.Final(digest); if (memcmp(digest, m_digest, SHA256::HASHLEN) == 0) { // clear & reset wxTheClipboard->Clear(); memset(m_digest, 0, SHA256::HASHLEN); m_set = false; // Also trash data in buffer and clipboard somehow? pws_os::Trace0(L"Cleared our data from buffer.\n"); } else{ pws_os::Trace0(L"Buffer doesn't contain our data. Nothing to clear.\n"); } } } wxTheClipboard->Close(); } return !m_set; } #if defined(__X__) || defined(__WXGTK__) /** * Set current clipboard buffer * @param primary if set to \c true, will use PRIMARY selection, otherwise CLIPBOARD X11 * @param clearOnChange if set to \c true, our previous data will be cleared from previous buffer */ void PWSclipboard::UsePrimarySelection(bool primary, bool clearOnChange) { if (primary != wxTheClipboard->IsUsingPrimarySelection()) { if (clearOnChange) ClearData(); wxTheClipboard->UsePrimarySelection(primary); } } #endif <commit_msg>spelling: remember<commit_after>/* * Copyright (c) 2003-2016 Rony Shapiro <[email protected]>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ #include <wx/clipbrd.h> #include <wx/dataobj.h> /* NOTE: In VS2013 wxWidgets 3.0.x builds: Both <wx/clipbrd.h> & <wx/dataobj.h> cause 51 warnings about using unsecure versions of standard calls, such as 'wcscpy' instead of 'wcscpy_s', if any previously included header file includes <string> even though pre-processor variables _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES and _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT are defined. The solution is to ensure that any header files containing <string>, e.g. "core/StringX.h", are placed after these two wxWidgets include statements. This issue did not occur with wxWidgets 2.8.12. For this reason, "pwsclip.h", which includes "core/StringX.h" that also includes <string>, is placed here after <wx/clipbrd.h> & <wx/dataobj.h>. */ #include "pwsclip.h" #ifdef __WXMSW__ #include <wx/msw/msvcrt.h> #endif PWSclipboard *PWSclipboard::self = nullptr; /** * Get pointer to single instance of clipboard manager */ PWSclipboard *PWSclipboard::GetInstance() { if (self == nullptr) { self = new PWSclipboard(); } return self; } /** * Destroy the instance */ void PWSclipboard::DeleteInstance() { delete self; self = nullptr; } PWSclipboard::PWSclipboard(): m_set(false) { memset(m_digest, 0, sizeof(m_digest)); } /** * Put text data to clipboard * @param[in] data data to store in clipboard * @param isSensitive if data sensitive, we remember its hash and will clear on ClearData() call * @return \c true, if we could open the clipboard and put the data */ bool PWSclipboard::SetData(const StringX &data) { wxMutexLocker clip(m_clipboardMutex); bool res = false; if (wxTheClipboard->Open()) { res = wxTheClipboard->SetData(new wxTextDataObject(data.c_str())); wxTheClipboard->Close(); } m_set = true; if (res) { // identify data in clipboard as ours, so as not to clear the wrong data later // of course, we don't want an extra copy of a password floating around // in memory, so we'll use the hash SHA256 ctx; const wchar_t *str = data.c_str(); ctx.Update(reinterpret_cast<const unsigned char *>(str), data.length()*sizeof(wchar_t)); ctx.Final(m_digest); } return res; } /** * Clear from clipboard data, that we put there previously * @return \c true, if we cleared our data, or stored data don't belong to us */ bool PWSclipboard::ClearData() { wxMutexLocker clip(m_clipboardMutex); if (m_set && wxTheClipboard->Open()) { wxTextDataObject obj; if (wxTheClipboard->IsSupported(wxDF_UNICODETEXT) && wxTheClipboard->GetData(obj)) { StringX buf(obj.GetText().data(), obj.GetText().size()); if (buf.length()) { // check if the data on the clipboard is the same we put there unsigned char digest[SHA256::HASHLEN]; SHA256 ctx; ctx.Update(reinterpret_cast<const unsigned char *>(buf.c_str()), buf.length()*sizeof(wchar_t)); ctx.Final(digest); if (memcmp(digest, m_digest, SHA256::HASHLEN) == 0) { // clear & reset wxTheClipboard->Clear(); memset(m_digest, 0, SHA256::HASHLEN); m_set = false; // Also trash data in buffer and clipboard somehow? pws_os::Trace0(L"Cleared our data from buffer.\n"); } else{ pws_os::Trace0(L"Buffer doesn't contain our data. Nothing to clear.\n"); } } } wxTheClipboard->Close(); } return !m_set; } #if defined(__X__) || defined(__WXGTK__) /** * Set current clipboard buffer * @param primary if set to \c true, will use PRIMARY selection, otherwise CLIPBOARD X11 * @param clearOnChange if set to \c true, our previous data will be cleared from previous buffer */ void PWSclipboard::UsePrimarySelection(bool primary, bool clearOnChange) { if (primary != wxTheClipboard->IsUsingPrimarySelection()) { if (clearOnChange) ClearData(); wxTheClipboard->UsePrimarySelection(primary); } } #endif <|endoftext|>
<commit_before>#include "RadixSort.h" #include <random> RadixSort::RadixSort (GLuint _numblocks) : blocksize (512), numblocks (_numblocks) { counting.CompileShader (GL_COMPUTE_SHADER, "shaders/radixsort/counting.glsl", "shaders/simulation/include.glsl"); counting.Link (); blockscan.CompileShader (GL_COMPUTE_SHADER, "shaders/radixsort/blockscan.glsl", "shaders/simulation/include.glsl"); blockscan.Link (); globalsort.CompileShader (GL_COMPUTE_SHADER, "shaders/radixsort/globalsort.glsl", "shaders/simulation/include.glsl"); globalsort.Link (); addblocksum.CompileShader (GL_COMPUTE_SHADER, "shaders/radixsort/addblocksum.glsl", "shaders/simulation/include.glsl"); addblocksum.Link (); glGenBuffers (3, buffers); glBindBuffer (GL_SHADER_STORAGE_BUFFER, buffer); glBufferData (GL_SHADER_STORAGE_BUFFER, sizeof (particleinfo_t) * blocksize * numblocks, NULL, GL_DYNAMIC_DRAW); glBindBuffer (GL_SHADER_STORAGE_BUFFER, prefixsums); glBufferData (GL_SHADER_STORAGE_BUFFER, sizeof (uint32_t) * blocksize * numblocks, NULL, GL_DYNAMIC_DRAW); uint32_t numblocksums = 4 * numblocks; { int n = ceil (log (((numblocksums + blocksize - 1) / blocksize) * blocksize) / log (blocksize)); n++; blocksums.resize (n); glGenBuffers (n, &blocksums[0]); } for (GLuint &blocksum : blocksums) { glBindBuffer (GL_SHADER_STORAGE_BUFFER, blocksum); numblocksums = ((numblocksums + blocksize - 1) / blocksize) * blocksize; if (numblocksums < 1) numblocksums = 1; glBufferData (GL_SHADER_STORAGE_BUFFER, sizeof (uint32_t) * numblocksums, NULL, GL_STATIC_DRAW); numblocksums /= blocksize; } glBindBuffer (GL_SHADER_STORAGE_BUFFER, result); glBufferData (GL_SHADER_STORAGE_BUFFER, sizeof (particleinfo_t) * blocksize * numblocks, NULL, GL_STATIC_DRAW); glm::uvec4 blocksumoffsets (0, numblocks, numblocks * 2, numblocks * 3); glProgramUniform4uiv (counting.get (), counting.GetUniformLocation ("blocksumoffsets"), 1, glm::value_ptr (blocksumoffsets)); glProgramUniform4uiv (globalsort.get (), globalsort.GetUniformLocation ("blocksumoffsets"), 1, glm::value_ptr (blocksumoffsets)); counting_bitshift = counting.GetUniformLocation ("bitshift"); globalsort_bitshift = globalsort.GetUniformLocation ("bitshift"); for (int blocksum : blocksums) { glBindBuffer (GL_SHADER_STORAGE_BUFFER, blocksum); glClearBufferData (GL_SHADER_STORAGE_BUFFER, GL_RGBA32UI, GL_RGBA, GL_UNSIGNED_INT, NULL); } glMemoryBarrier (GL_BUFFER_UPDATE_BARRIER_BIT); } RadixSort::~RadixSort (void) { glDeleteBuffers (blocksums.size (), &blocksums[0]); glDeleteBuffers (3, buffers); } GLuint RadixSort::GetBuffer (void) { return buffer; } void RadixSort::Run (unsigned int numbits) { for (int i = 0; i < (numbits + 1) >> 1; i++) { SortBits (2 * i); std::swap (result, buffer); } std::swap (result, buffer); } uint32_t intpow (uint32_t x, uint32_t y) { uint32_t r = 1; while (y) { if (y & 1) r *= x; y >>= 1; x *= x; } return r; } void RadixSort::SortBits (int bits) { glProgramUniform1i (counting.get (), counting_bitshift, bits); glProgramUniform1i (globalsort.get (), globalsort_bitshift, bits); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 0, buffer); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 1, prefixsums); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 2, blocksums.front ()); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 3, result); counting.Use (); glDispatchCompute (numblocks, 1, 1); glMemoryBarrier (GL_SHADER_STORAGE_BARRIER_BIT); blockscan.Use (); uint32_t numblocksums = (4 * numblocks) / blocksize; for (int i = 0; i < blocksums.size () - 1; i++) { glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 0, blocksums[i]); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 1, blocksums[i + 1]); glDispatchCompute (numblocksums > 0 ? numblocksums : 1, 1, 1); numblocksums /= blocksize; glMemoryBarrier (GL_SHADER_STORAGE_BARRIER_BIT); } addblocksum.Use (); for (int i = blocksums.size () - 3; i >= 0; i--) { uint32_t numblocksums = (4 * numblocks) / intpow (blocksize, i + 1); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 0, blocksums[i]); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 1, blocksums[i + 1]); glDispatchCompute (numblocksums > 0 ? numblocksums : 1, 1, 1); glMemoryBarrier (GL_SHADER_STORAGE_BARRIER_BIT); } glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 0, buffer); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 1, prefixsums); globalsort.Use (); glDispatchCompute (numblocks, 1, 1); glMemoryBarrier (GL_SHADER_STORAGE_BARRIER_BIT); } <commit_msg>Remove invalid buffer swapping.<commit_after>#include "RadixSort.h" #include <random> RadixSort::RadixSort (GLuint _numblocks) : blocksize (512), numblocks (_numblocks) { counting.CompileShader (GL_COMPUTE_SHADER, "shaders/radixsort/counting.glsl", "shaders/simulation/include.glsl"); counting.Link (); blockscan.CompileShader (GL_COMPUTE_SHADER, "shaders/radixsort/blockscan.glsl", "shaders/simulation/include.glsl"); blockscan.Link (); globalsort.CompileShader (GL_COMPUTE_SHADER, "shaders/radixsort/globalsort.glsl", "shaders/simulation/include.glsl"); globalsort.Link (); addblocksum.CompileShader (GL_COMPUTE_SHADER, "shaders/radixsort/addblocksum.glsl", "shaders/simulation/include.glsl"); addblocksum.Link (); glGenBuffers (3, buffers); glBindBuffer (GL_SHADER_STORAGE_BUFFER, buffer); glBufferData (GL_SHADER_STORAGE_BUFFER, sizeof (particleinfo_t) * blocksize * numblocks, NULL, GL_DYNAMIC_DRAW); glBindBuffer (GL_SHADER_STORAGE_BUFFER, prefixsums); glBufferData (GL_SHADER_STORAGE_BUFFER, sizeof (uint32_t) * blocksize * numblocks, NULL, GL_DYNAMIC_DRAW); uint32_t numblocksums = 4 * numblocks; { int n = ceil (log (((numblocksums + blocksize - 1) / blocksize) * blocksize) / log (blocksize)); n++; blocksums.resize (n); glGenBuffers (n, &blocksums[0]); } for (GLuint &blocksum : blocksums) { glBindBuffer (GL_SHADER_STORAGE_BUFFER, blocksum); numblocksums = ((numblocksums + blocksize - 1) / blocksize) * blocksize; if (numblocksums < 1) numblocksums = 1; glBufferData (GL_SHADER_STORAGE_BUFFER, sizeof (uint32_t) * numblocksums, NULL, GL_STATIC_DRAW); numblocksums /= blocksize; } glBindBuffer (GL_SHADER_STORAGE_BUFFER, result); glBufferData (GL_SHADER_STORAGE_BUFFER, sizeof (particleinfo_t) * blocksize * numblocks, NULL, GL_STATIC_DRAW); glm::uvec4 blocksumoffsets (0, numblocks, numblocks * 2, numblocks * 3); glProgramUniform4uiv (counting.get (), counting.GetUniformLocation ("blocksumoffsets"), 1, glm::value_ptr (blocksumoffsets)); glProgramUniform4uiv (globalsort.get (), globalsort.GetUniformLocation ("blocksumoffsets"), 1, glm::value_ptr (blocksumoffsets)); counting_bitshift = counting.GetUniformLocation ("bitshift"); globalsort_bitshift = globalsort.GetUniformLocation ("bitshift"); for (int blocksum : blocksums) { glBindBuffer (GL_SHADER_STORAGE_BUFFER, blocksum); glClearBufferData (GL_SHADER_STORAGE_BUFFER, GL_RGBA32UI, GL_RGBA, GL_UNSIGNED_INT, NULL); } glMemoryBarrier (GL_BUFFER_UPDATE_BARRIER_BIT); } RadixSort::~RadixSort (void) { glDeleteBuffers (blocksums.size (), &blocksums[0]); glDeleteBuffers (3, buffers); } GLuint RadixSort::GetBuffer (void) { return buffer; } void RadixSort::Run (unsigned int numbits) { for (int i = 0; i < (numbits + 1) >> 1; i++) { SortBits (2 * i); std::swap (result, buffer); } } uint32_t intpow (uint32_t x, uint32_t y) { uint32_t r = 1; while (y) { if (y & 1) r *= x; y >>= 1; x *= x; } return r; } void RadixSort::SortBits (int bits) { glProgramUniform1i (counting.get (), counting_bitshift, bits); glProgramUniform1i (globalsort.get (), globalsort_bitshift, bits); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 0, buffer); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 1, prefixsums); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 2, blocksums.front ()); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 3, result); counting.Use (); glDispatchCompute (numblocks, 1, 1); glMemoryBarrier (GL_SHADER_STORAGE_BARRIER_BIT); blockscan.Use (); uint32_t numblocksums = (4 * numblocks) / blocksize; for (int i = 0; i < blocksums.size () - 1; i++) { glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 0, blocksums[i]); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 1, blocksums[i + 1]); glDispatchCompute (numblocksums > 0 ? numblocksums : 1, 1, 1); numblocksums /= blocksize; glMemoryBarrier (GL_SHADER_STORAGE_BARRIER_BIT); } addblocksum.Use (); for (int i = blocksums.size () - 3; i >= 0; i--) { uint32_t numblocksums = (4 * numblocks) / intpow (blocksize, i + 1); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 0, blocksums[i]); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 1, blocksums[i + 1]); glDispatchCompute (numblocksums > 0 ? numblocksums : 1, 1, 1); glMemoryBarrier (GL_SHADER_STORAGE_BARRIER_BIT); } glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 0, buffer); glBindBufferBase (GL_SHADER_STORAGE_BUFFER, 1, prefixsums); globalsort.Use (); glDispatchCompute (numblocks, 1, 1); glMemoryBarrier (GL_SHADER_STORAGE_BARRIER_BIT); } <|endoftext|>
<commit_before>/* Copyright 2017 Jonathan Bayle, Thomas Medioni Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <iostream> #include "map.hpp" #include "tmx/tmx.h" extern "C" { // Loads a bitmap and return pointer, used by TMX void* al_img_loader(const char *path) { ALLEGRO_BITMAP *res = NULL; ALLEGRO_PATH *alpath = NULL; if (!(alpath = al_create_path(path))) return NULL; al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_WITH_ALPHA); res = al_load_bitmap(al_path_cstr(alpath, ALLEGRO_NATIVE_PATH_SEP)); al_destroy_path(alpath); return reinterpret_cast<void*> (res); } } // extern "C" static int gid_extract_flags(unsigned int gid) { int res = 0; if (gid & TMX_FLIPPED_HORIZONTALLY) res |= ALLEGRO_FLIP_HORIZONTAL; if (gid & TMX_FLIPPED_VERTICALLY) res |= ALLEGRO_FLIP_VERTICAL; /* FIXME allegro has no diagonal flip */ return res; } static unsigned int gid_clear_flags(unsigned int gid) { return gid & TMX_FLIP_BITS_REMOVAL; } static void draw_layer(tmx_map *map, tmx_layer *layer) { unsigned long i, j; unsigned int gid, x, y, w, h, flags; float op; tmx_tileset *ts; tmx_image *im; ALLEGRO_BITMAP *tileset; op = layer->opacity; for (i = 0; i < map->height; i++) { for (j = 0; j < map->width; j++) { gid = gid_clear_flags(layer->content.gids[(i * map->width) + j]); if (map->tiles[gid] != NULL) { ts = map->tiles[gid]->tileset; im = map->tiles[gid]->image; x = map->tiles[gid]->ul_x; y = map->tiles[gid]->ul_y; w = ts->tile_width; h = ts->tile_height; if (im) { tileset = (ALLEGRO_BITMAP*) im->resource_image; } else { tileset = (ALLEGRO_BITMAP*) ts->image->resource_image; } flags = gid_extract_flags(layer->content.gids[(i * map->width) + j]); al_draw_tinted_bitmap_region(tileset, al_map_rgba_f(op, op, op, op), x, y, w, h, j * ts->tile_width, i * ts->tile_height, flags); } } } } static void draw_all_layers(tmx_map *map, tmx_layer *layers) { while (layers) { if (layers->visible) { if (layers->type == L_GROUP) { draw_all_layers(map, layers->content.group_head); } else if (layers->type == L_IMAGE) { if (layers->opacity < 1.) { float op = layers->opacity; al_draw_tinted_bitmap((ALLEGRO_BITMAP*) layers->content.image->resource_image, al_map_rgba_f(op, op, op, op), 0, 0, 0); } al_draw_bitmap((ALLEGRO_BITMAP*) layers->content.image->resource_image, 0, 0, 0); } else if (layers->type == L_LAYER) { draw_layer(map, layers); } } layers = layers->next; } } ALLEGRO_COLOR int_to_al_color(int color) { unsigned char r, g, b; r = (color >> 16) & 0xFF; g = (color >> 8) & 0xFF; b = (color) & 0xFF; return al_map_rgb(r, g, b); } void map::initialize() { tmx_img_load_func = al_img_loader; tmx_img_free_func = (void (*)(void*))al_destroy_bitmap; } map::map(const char* map_location) { tmx_map *loaded_map = tmx_load(map_location); vivace::runtime_assert(loaded_map, tmx_strerr()); width = loaded_map->width * loaded_map->tile_width; height = loaded_map->height * loaded_map->tile_height; // Render all graphic layers to a bitmap bitmap = std::unique_ptr<ALLEGRO_BITMAP, al_bitmap_deleter>(al_create_bitmap(width, height)); ALLEGRO_BITMAP *restore = al_get_target_bitmap(); al_set_target_bitmap(bitmap.get()); draw_all_layers(loaded_map, loaded_map->ly_head); al_set_target_bitmap(restore); // Copy tracks tmx_layer *obj_layer = loaded_map->ly_head->next; vivace::runtime_assert(obj_layer->type == L_OBJGR, "second layer is not an objgr layer"); tmx_object *pos = obj_layer->content.objgr->head; while (pos) { vivace::runtime_assert(pos->obj_type == OT_POLYLINE, "object is not a polyline"); track track_item(pos->content.shape->points, pos->content.shape->points_len, pos->x, pos->y); tracks.insert(tracks.begin(), track_item); pos = pos->next; } bg_color = int_to_al_color(loaded_map->backgroundcolor); tmx_map_free(loaded_map); }; // Direction _MUST_ be normalized! static double compute_rotation(glm::dvec2 direction) { glm::dvec2 orient(0, -1); double angle = glm::acos(glm::dot(direction, orient)); return angle * (((direction.x * orient.y) >= 0)? 1: -1); } static glm::vec2 compute_direction(glm::dvec2 from, glm::vec2 to) { return glm::normalize(glm::dvec2(to.x - from.x, to.y - from.y)); } track::track(double** points, int points_len, double off_x, double off_y) { for (int it=0; it<points_len; it++) { double x, y; x = off_x + points[it][0]; y = off_y + points[it][1]; #ifndef NDEBUG std::cout << "tracks point " << it+1 << " (x, y) = " << x << ", " << y << std::endl; #endif this->points.push_back(glm::dvec2(x, y)); } // Compute length of all segments, distance_to_next and direction_to_next and map_rotation for each segment this->length = 0.; for (int it=1; it<points_len; it++) { glm::dvec2 &point = this->points.at(it); glm::dvec2 &prev = this->points.at(it - 1); double dist = glm::distance<double>(point, prev); distance_to_next.push_back(dist); length += dist; glm::dvec2 dir = compute_direction(prev, point); direction_to_next.push_back(dir); map_rotation.push_back(compute_rotation(dir)); } #ifndef NDEBUG std::cout << "length of track = " << length << std::endl; #endif } double track::get_16px_percentage() { return 1./(length/16.); } glm::dvec3 track::get_position(track& reference, double completion_percentage) const { if (completion_percentage <= 0.) { return glm::dvec3(points.front(), map_rotation.front()); } if (completion_percentage >= 1.) { return glm::dvec3(points.back(), map_rotation.back()); } double real_length = completion_percentage * reference.length; for (std::vector<double>::size_type it=0; it<reference.distance_to_next.size(); it++) { double dist = reference.distance_to_next.at(it); if (dist < real_length) { real_length -= dist; } else { glm::dvec2 point = points.at(it); if (real_length < 1e-6) { return glm::dvec3(point, map_rotation.at(it)); } double segment_completion = real_length / dist; glm::dvec2 direction = direction_to_next.at(it); real_length = segment_completion * distance_to_next.at(it); return glm::dvec3(point + (real_length * direction), map_rotation.at(it)); } } return glm::dvec3(points.back(), map_rotation.back()); } <commit_msg>Smooth rotations<commit_after>/* Copyright 2017 Jonathan Bayle, Thomas Medioni Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <iostream> #include "map.hpp" #include "tmx/tmx.h" extern "C" { // Loads a bitmap and return pointer, used by TMX void* al_img_loader(const char *path) { ALLEGRO_BITMAP *res = NULL; ALLEGRO_PATH *alpath = NULL; if (!(alpath = al_create_path(path))) return NULL; al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_WITH_ALPHA); res = al_load_bitmap(al_path_cstr(alpath, ALLEGRO_NATIVE_PATH_SEP)); al_destroy_path(alpath); return reinterpret_cast<void*> (res); } } // extern "C" static int gid_extract_flags(unsigned int gid) { int res = 0; if (gid & TMX_FLIPPED_HORIZONTALLY) res |= ALLEGRO_FLIP_HORIZONTAL; if (gid & TMX_FLIPPED_VERTICALLY) res |= ALLEGRO_FLIP_VERTICAL; /* FIXME allegro has no diagonal flip */ return res; } static unsigned int gid_clear_flags(unsigned int gid) { return gid & TMX_FLIP_BITS_REMOVAL; } static void draw_layer(tmx_map *map, tmx_layer *layer) { unsigned long i, j; unsigned int gid, x, y, w, h, flags; float op; tmx_tileset *ts; tmx_image *im; ALLEGRO_BITMAP *tileset; op = layer->opacity; for (i = 0; i < map->height; i++) { for (j = 0; j < map->width; j++) { gid = gid_clear_flags(layer->content.gids[(i * map->width) + j]); if (map->tiles[gid] != NULL) { ts = map->tiles[gid]->tileset; im = map->tiles[gid]->image; x = map->tiles[gid]->ul_x; y = map->tiles[gid]->ul_y; w = ts->tile_width; h = ts->tile_height; if (im) { tileset = (ALLEGRO_BITMAP*) im->resource_image; } else { tileset = (ALLEGRO_BITMAP*) ts->image->resource_image; } flags = gid_extract_flags(layer->content.gids[(i * map->width) + j]); al_draw_tinted_bitmap_region(tileset, al_map_rgba_f(op, op, op, op), x, y, w, h, j * ts->tile_width, i * ts->tile_height, flags); } } } } static void draw_all_layers(tmx_map *map, tmx_layer *layers) { while (layers) { if (layers->visible) { if (layers->type == L_GROUP) { draw_all_layers(map, layers->content.group_head); } else if (layers->type == L_IMAGE) { if (layers->opacity < 1.) { float op = layers->opacity; al_draw_tinted_bitmap((ALLEGRO_BITMAP*) layers->content.image->resource_image, al_map_rgba_f(op, op, op, op), 0, 0, 0); } al_draw_bitmap((ALLEGRO_BITMAP*) layers->content.image->resource_image, 0, 0, 0); } else if (layers->type == L_LAYER) { draw_layer(map, layers); } } layers = layers->next; } } ALLEGRO_COLOR int_to_al_color(int color) { unsigned char r, g, b; r = (color >> 16) & 0xFF; g = (color >> 8) & 0xFF; b = (color) & 0xFF; return al_map_rgb(r, g, b); } void map::initialize() { tmx_img_load_func = al_img_loader; tmx_img_free_func = (void (*)(void*))al_destroy_bitmap; } map::map(const char* map_location) { tmx_map *loaded_map = tmx_load(map_location); vivace::runtime_assert(loaded_map, tmx_strerr()); width = loaded_map->width * loaded_map->tile_width; height = loaded_map->height * loaded_map->tile_height; // Render all graphic layers to a bitmap bitmap = std::unique_ptr<ALLEGRO_BITMAP, al_bitmap_deleter>(al_create_bitmap(width, height)); ALLEGRO_BITMAP *restore = al_get_target_bitmap(); al_set_target_bitmap(bitmap.get()); draw_all_layers(loaded_map, loaded_map->ly_head); al_set_target_bitmap(restore); // Copy tracks tmx_layer *obj_layer = loaded_map->ly_head->next; vivace::runtime_assert(obj_layer->type == L_OBJGR, "second layer is not an objgr layer"); tmx_object *pos = obj_layer->content.objgr->head; while (pos) { vivace::runtime_assert(pos->obj_type == OT_POLYLINE, "object is not a polyline"); track track_item(pos->content.shape->points, pos->content.shape->points_len, pos->x, pos->y); tracks.insert(tracks.begin(), track_item); pos = pos->next; } bg_color = int_to_al_color(loaded_map->backgroundcolor); tmx_map_free(loaded_map); }; // Direction _MUST_ be normalized! static double compute_rotation(glm::dvec2 direction) { glm::dvec2 orient(0, -1); double angle = glm::acos(glm::dot(direction, orient)); return angle * (((direction.x * orient.y) >= 0)? 1: -1); } static glm::vec2 compute_direction(glm::dvec2 from, glm::vec2 to) { return glm::normalize(glm::dvec2(to.x - from.x, to.y - from.y)); } track::track(double** points, int points_len, double off_x, double off_y) { for (int it=0; it<points_len; it++) { double x, y; x = off_x + points[it][0]; y = off_y + points[it][1]; #ifndef NDEBUG std::cout << "tracks point " << it+1 << " (x, y) = " << x << ", " << y << std::endl; #endif this->points.push_back(glm::dvec2(x, y)); } // Compute length of all segments, distance_to_next and direction_to_next and map_rotation for each segment this->length = 0.; for (int it=1; it<points_len; it++) { glm::dvec2 &point = this->points.at(it); glm::dvec2 &prev = this->points.at(it - 1); double dist = glm::distance<double>(point, prev); distance_to_next.push_back(dist); length += dist; glm::dvec2 dir = compute_direction(prev, point); direction_to_next.push_back(dir); map_rotation.push_back(compute_rotation(dir)); #ifndef NDEBUG std::cout << "segment [" << it-1 << ", " << it << "] length=" << distance_to_next[it-1] << " map rotation=" << map_rotation[it-1] << std::endl; #endif } #ifndef NDEBUG std::cout << "length of track = " << length << std::endl; #endif } double track::get_16px_percentage() { return 1./(length/16.); } // returns 0.0 at next-16px to next, 0.5 at next, 0.5 at previous, 1.0 at previous+16px static double compute_proximity_ratio(glm::dvec2 pos, glm::dvec2 prev_point, glm::dvec2 next_point) { double dist_to_next = glm::distance(pos, next_point); double dist_from_prev = glm::distance(prev_point, pos); if (dist_to_next <= 16) { return 0.5 - dist_to_next/32.; } if (dist_from_prev <= 16) { return 0.5 + dist_from_prev/32.; } return 1.; } #define PI 3.141592653589793 // to smooth rotation according to the proximity ratio // prev_angle must be the map rotation engle of the segment BEFORE the proximal point // next_angle must be the map rotation engle of the segment AFTER the proximal point static double apply_proximity_ratio(double prox_ratio, double prev_angle, double next_angle) { double rotation = (next_angle - prev_angle); if (rotation > PI) { rotation = PI - rotation; } if (rotation < -PI) { rotation = -rotation - PI; } return prev_angle + prox_ratio * rotation; } glm::dvec3 track::get_position(track& reference, double completion_percentage) const { if (completion_percentage <= 0.) { return glm::dvec3(points.front(), map_rotation.front()); } if (completion_percentage >= 1.) { return glm::dvec3(points.back(), map_rotation.back()); } double real_length = completion_percentage * reference.length; std::vector<double>::size_type last = reference.distance_to_next.size() - 1; for (std::vector<double>::size_type it=0; it<=last; it++) { double dist = reference.distance_to_next[it]; if (dist < real_length) { real_length -= dist; } else { glm::dvec2 point = points[it]; if (real_length < 1e-6) { if (it == 0 || it == last) { return glm::dvec3(point, map_rotation[it]); } // Smooth angle double angle = apply_proximity_ratio(0.5, map_rotation[it-1], map_rotation[it]); return glm::dvec3(point, angle); } double segment_completion = real_length / dist; // percentage of completion of current segment on reference track glm::dvec2 direction = direction_to_next[it]; real_length = segment_completion * distance_to_next[it]; // apply %age of completion to same segment on this track glm::dvec2 position = point + (real_length * direction); // Smooth angle double angle = map_rotation[it]; double prox_ratio = compute_proximity_ratio(position, point, points[it+1]); if (it < last && prox_ratio > 0. && prox_ratio < 0.5) { angle = apply_proximity_ratio(prox_ratio, map_rotation[it], map_rotation[it+1]); } else if (it > 0 && prox_ratio < 1. && prox_ratio >= 0.5) { angle = apply_proximity_ratio(prox_ratio, map_rotation[it-1], map_rotation[it]); } return glm::dvec3(position, angle); } } return glm::dvec3(points.back(), map_rotation.back()); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include <QVariant> #include <QColor> #include "bindingproperty.h" #include "nodeproperty.h" #include "nodelistproperty.h" #include "qmltextgenerator.h" #include "variantproperty.h" #include <nodemetainfo.h> #include "model.h" using namespace QmlDesigner; using namespace QmlDesigner::Internal; inline static QString properColorName(const QColor &color) { QString s; if (color.alpha() == 255) s.sprintf("#%02x%02x%02x", color.red(), color.green(), color.blue()); else s.sprintf("#%02x%02x%02x%02x", color.alpha(), color.red(), color.green(), color.blue()); return s; } inline static QString doubleToString(double d) { QString string = QString::number(d, 'f', 3); if (string.endsWith(".000")) string.chop(4); return string; } QmlTextGenerator::QmlTextGenerator(const QStringList &propertyOrder, int indentDepth): m_propertyOrder(propertyOrder), m_indentDepth(indentDepth) { } QString QmlTextGenerator::toQml(const AbstractProperty &property, int indentDepth) const { if (property.isBindingProperty()) { return property.toBindingProperty().expression(); } else if (property.isNodeProperty()) { return toQml(property.toNodeProperty().modelNode(), indentDepth); } else if (property.isNodeListProperty()) { const QList<ModelNode> nodes = property.toNodeListProperty().toModelNodeList(); if (property.isDefaultProperty()) { QString result; for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1String("\n\n"); result += QString(indentDepth, QLatin1Char(' ')); result += toQml(nodes.at(i), indentDepth); } return result; } else { QString result = QLatin1String("["); const int arrayContentDepth = indentDepth + 4; const QString arrayContentIndentation(arrayContentDepth, QLatin1Char(' ')); for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1Char(','); result += QLatin1Char('\n'); result += arrayContentIndentation; result += toQml(nodes.at(i), arrayContentDepth); } return result + QLatin1Char(']'); } } else if (property.isVariantProperty()) { const VariantProperty variantProperty = property.toVariantProperty(); const QVariant value = variantProperty.value(); const QString stringValue = value.toString(); if (property.name() == QLatin1String("id")) return stringValue; if (false) { } if (variantProperty.parentModelNode().metaInfo().isValid() && variantProperty.parentModelNode().metaInfo().propertyIsEnumType(variantProperty.name())) { return variantProperty.parentModelNode().metaInfo().propertyEnumScope(variantProperty.name()) + '.' + stringValue; } else { switch (value.type()) { case QVariant::Bool: if (value.value<bool>()) return QLatin1String("true"); else return QLatin1String("false"); case QVariant::Color: return QString(QLatin1String("\"%1\"")).arg(properColorName(value.value<QColor>())); case QVariant::Double: return doubleToString(value.toDouble()); case QVariant::Int: case QVariant::LongLong: case QVariant::UInt: case QVariant::ULongLong: return stringValue; default: return QString(QLatin1String("\"%1\"")).arg(escape(stringValue)); } } } else { Q_ASSERT("Unknown property type"); return QString(); } } QString QmlTextGenerator::toQml(const ModelNode &node, int indentDepth) const { QString type = node.type(); QString url; if (type.contains('.')) { QStringList nameComponents = type.split('.'); url = nameComponents.first(); type = nameComponents.last(); } QString alias; if (!url.isEmpty()) { const QString &versionUrl = QString("%1.%2").arg(QString::number(node.majorVersion()), QString::number(node.minorVersion())); foreach (const Import &import, node.model()->imports()) { if (import.url() == url && import.version() == versionUrl) { alias = import.alias(); break; } } } QString result; if (!alias.isEmpty()) result = alias + '.'; result += type; result += QLatin1String(" {\n"); const int propertyIndentDepth = indentDepth + 4; const QString properties = propertiesToQml(node, propertyIndentDepth); return result + properties + QString(indentDepth, QLatin1Char(' ')) + QLatin1Char('}'); } QString QmlTextGenerator::propertiesToQml(const ModelNode &node, int indentDepth) const { QString topPart; QString bottomPart; QStringList nodePropertyNames = node.propertyNames(); bool addToTop = true; foreach (const QString &propertyName, m_propertyOrder) { if (QLatin1String("id") == propertyName) { // the model handles the id property special, so: if (!node.id().isEmpty()) { QString idLine(indentDepth, QLatin1Char(' ')); idLine += QLatin1String("id: "); idLine += node.id(); idLine += QLatin1Char('\n'); if (addToTop) topPart.append(idLine); else bottomPart.append(idLine); } } else if (propertyName.isEmpty()) { addToTop = false; } else if (nodePropertyNames.removeAll(propertyName)) { const QString newContent = propertyToQml(node.property(propertyName), indentDepth); if (addToTop) topPart.append(newContent); else bottomPart.append(newContent); } } foreach (const QString &propertyName, nodePropertyNames) { bottomPart.prepend(propertyToQml(node.property(propertyName), indentDepth)); } return topPart + bottomPart; } QString QmlTextGenerator::propertyToQml(const AbstractProperty &property, int indentDepth) const { QString result; if (property.isDefaultProperty()) result = toQml(property, indentDepth); else result = QString(indentDepth, QLatin1Char(' ')) + property.name() + QLatin1String(": ") + toQml(property, indentDepth); result += QLatin1Char('\n'); return result; } QString QmlTextGenerator::escape(const QString &value) { QString result = value; result.replace(QLatin1String("\\"), QLatin1String("\\\\")); result.replace(QLatin1String("\""), QLatin1String("\\\"")); result.replace(QLatin1String("\t"), QLatin1String("\\t")); result.replace(QLatin1String("\r"), QLatin1String("\\r")); result.replace(QLatin1String("\n"), QLatin1String("\\n")); return result; } <commit_msg>QmlDesigner: fix regression in string rewriting<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include <QVariant> #include <QColor> #include "bindingproperty.h" #include "nodeproperty.h" #include "nodelistproperty.h" #include "qmltextgenerator.h" #include "variantproperty.h" #include <nodemetainfo.h> #include "model.h" using namespace QmlDesigner; using namespace QmlDesigner::Internal; inline static QString properColorName(const QColor &color) { QString s; if (color.alpha() == 255) s.sprintf("#%02x%02x%02x", color.red(), color.green(), color.blue()); else s.sprintf("#%02x%02x%02x%02x", color.alpha(), color.red(), color.green(), color.blue()); return s; } inline static QString doubleToString(double d) { QString string = QString::number(d, 'f', 3); if (string.contains(QLatin1Char('.'))) { while (string.at(string.length()- 1) == QLatin1Char('0')) string.chop(1); if (string.at(string.length()- 1) == QLatin1Char('.')) string.chop(1); } return string; } QmlTextGenerator::QmlTextGenerator(const QStringList &propertyOrder, int indentDepth): m_propertyOrder(propertyOrder), m_indentDepth(indentDepth) { } QString QmlTextGenerator::toQml(const AbstractProperty &property, int indentDepth) const { if (property.isBindingProperty()) { return property.toBindingProperty().expression(); } else if (property.isNodeProperty()) { return toQml(property.toNodeProperty().modelNode(), indentDepth); } else if (property.isNodeListProperty()) { const QList<ModelNode> nodes = property.toNodeListProperty().toModelNodeList(); if (property.isDefaultProperty()) { QString result; for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1String("\n\n"); result += QString(indentDepth, QLatin1Char(' ')); result += toQml(nodes.at(i), indentDepth); } return result; } else { QString result = QLatin1String("["); const int arrayContentDepth = indentDepth + 4; const QString arrayContentIndentation(arrayContentDepth, QLatin1Char(' ')); for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1Char(','); result += QLatin1Char('\n'); result += arrayContentIndentation; result += toQml(nodes.at(i), arrayContentDepth); } return result + QLatin1Char(']'); } } else if (property.isVariantProperty()) { const VariantProperty variantProperty = property.toVariantProperty(); const QVariant value = variantProperty.value(); const QString stringValue = value.toString(); if (property.name() == QLatin1String("id")) return stringValue; if (false) { } if (variantProperty.parentModelNode().metaInfo().isValid() && variantProperty.parentModelNode().metaInfo().propertyIsEnumType(variantProperty.name())) { return variantProperty.parentModelNode().metaInfo().propertyEnumScope(variantProperty.name()) + '.' + stringValue; } else { switch (value.type()) { case QVariant::Bool: if (value.value<bool>()) return QLatin1String("true"); else return QLatin1String("false"); case QVariant::Color: return QString(QLatin1String("\"%1\"")).arg(properColorName(value.value<QColor>())); case QVariant::Double: return doubleToString(value.toDouble()); case QVariant::Int: case QVariant::LongLong: case QVariant::UInt: case QVariant::ULongLong: return stringValue; default: return QString(QLatin1String("\"%1\"")).arg(escape(stringValue)); } } } else { Q_ASSERT("Unknown property type"); return QString(); } } QString QmlTextGenerator::toQml(const ModelNode &node, int indentDepth) const { QString type = node.type(); QString url; if (type.contains('.')) { QStringList nameComponents = type.split('.'); url = nameComponents.first(); type = nameComponents.last(); } QString alias; if (!url.isEmpty()) { const QString &versionUrl = QString("%1.%2").arg(QString::number(node.majorVersion()), QString::number(node.minorVersion())); foreach (const Import &import, node.model()->imports()) { if (import.url() == url && import.version() == versionUrl) { alias = import.alias(); break; } } } QString result; if (!alias.isEmpty()) result = alias + '.'; result += type; result += QLatin1String(" {\n"); const int propertyIndentDepth = indentDepth + 4; const QString properties = propertiesToQml(node, propertyIndentDepth); return result + properties + QString(indentDepth, QLatin1Char(' ')) + QLatin1Char('}'); } QString QmlTextGenerator::propertiesToQml(const ModelNode &node, int indentDepth) const { QString topPart; QString bottomPart; QStringList nodePropertyNames = node.propertyNames(); bool addToTop = true; foreach (const QString &propertyName, m_propertyOrder) { if (QLatin1String("id") == propertyName) { // the model handles the id property special, so: if (!node.id().isEmpty()) { QString idLine(indentDepth, QLatin1Char(' ')); idLine += QLatin1String("id: "); idLine += node.id(); idLine += QLatin1Char('\n'); if (addToTop) topPart.append(idLine); else bottomPart.append(idLine); } } else if (propertyName.isEmpty()) { addToTop = false; } else if (nodePropertyNames.removeAll(propertyName)) { const QString newContent = propertyToQml(node.property(propertyName), indentDepth); if (addToTop) topPart.append(newContent); else bottomPart.append(newContent); } } foreach (const QString &propertyName, nodePropertyNames) { bottomPart.prepend(propertyToQml(node.property(propertyName), indentDepth)); } return topPart + bottomPart; } QString QmlTextGenerator::propertyToQml(const AbstractProperty &property, int indentDepth) const { QString result; if (property.isDefaultProperty()) result = toQml(property, indentDepth); else result = QString(indentDepth, QLatin1Char(' ')) + property.name() + QLatin1String(": ") + toQml(property, indentDepth); result += QLatin1Char('\n'); return result; } QString QmlTextGenerator::escape(const QString &value) { QString result = value; result.replace(QLatin1String("\\"), QLatin1String("\\\\")); result.replace(QLatin1String("\""), QLatin1String("\\\"")); result.replace(QLatin1String("\t"), QLatin1String("\\t")); result.replace(QLatin1String("\r"), QLatin1String("\\r")); result.replace(QLatin1String("\n"), QLatin1String("\\n")); return result; } <|endoftext|>
<commit_before>#include "RayTracer.hpp" #include "Tree.hpp" #include <ctime> //temporary variables Vec3Df testRayOrigin; Vec3Df testRayDestination; string mesh; extern unsigned int textures[2]; clock_t lastFrameTime; float fps; unsigned int framesSinceLastDraw = 30; string screenFPS; extern unsigned int previewResX; extern unsigned int previewResY; extern unsigned int msaa; extern unsigned int numThreads; extern Tree MyTree; //use this function for any preprocessing of the mesh. int init(int argc, char **argv){ // skip program name argv[0] if present argc -= (argc > 0); argv += (argc > 0); option::Stats stats(usage, argc, argv); option::Option* options = (option::Option*)calloc(stats.options_max, sizeof(option::Option)); option::Option* buffer = (option::Option*)calloc(stats.buffer_max, sizeof(option::Option)); option::Parser parse(usage, argc, argv, options, buffer); if(parse.error()) return 1; if(options[HELP]){ int columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80; option::printUsage(fwrite, stdout, usage, columns); return 2; } lastFrameTime = clock(); if(options[MESH]){ const char* arg = options[MESH].last()->arg; if(arg != 0){ mesh = arg; } }else{ mesh = "0"; } if(mesh == "0") mesh = "cube"; else if(mesh == "1") mesh = "simple_monkey"; else if(mesh == "2") mesh = "monkey"; else if(mesh == "3") mesh = "dodgeColorTest"; mesh = string("mesh/").append(mesh).append(".obj"); MyMesh.loadMesh(mesh.c_str(), true); MyMesh.computeVertexNormals(); MyTree.build(MyMesh); //one first move: initialize the first light source //at least ONE light source has to be in the scene!!! //here, we set it to the current location of the camera MyLightPositions.push_back(MyCameraPosition); if(options[RAYTRACE]){ startRayTracing(activeTexIndex, true); return 255; } return 0; } //transformer le x, y en position 3D void produceRay(int x_I, int y_I, Vec3Df * origin, Vec3Df * dest){ int viewport[4]; double modelview[16]; double projection[16]; //point sur near plane //double positionN[3]; //point sur far plane //double positionF[3]; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); //recuperer matrices glGetDoublev(GL_PROJECTION_MATRIX, projection); //recuperer matrices glGetIntegerv(GL_VIEWPORT, viewport); //viewport int y_new = viewport[3] - y_I; double x, y, z; gluUnProject(x_I, y_new, 0, modelview, projection, viewport, &x, &y, &z); origin->p[0] = float(x); origin->p[1] = float(y); origin->p[2] = float(z); gluUnProject(x_I, y_new, 1, modelview, projection, viewport, &x, &y, &z); dest->p[0] = float(x); dest->p[1] = float(y); dest->p[2] = float(z); } void produceRay(int x_I, int y_I, Vec3Df & origin, Vec3Df & dest){ produceRay(x_I, y_I, &origin, &dest); } Vec3Df origin00, dest00; Vec3Df origin01, dest01; Vec3Df origin10, dest10; Vec3Df origin11, dest11; #ifdef WIN32 #define linux false #else #define linux true #endif void raytracePart(Image* result, int w, int h, int xx, int yy, int ww, int hh){ Vec3Df origin, dest; for(float y = yy;y < hh;y++){ for(float x = xx;x < ww;x++){ //svp, decidez vous memes quels parametres vous allez passer à la fonction //c'est le stront a la plafond, c'est drôle //e.g., maillage, triangles, sphères etc. Vec3Df total(0, 0, 0); for(unsigned int xs = 0;xs < msaa;xs++){ for(unsigned int ys = 0;ys < msaa;ys++){ float xscale = 1.0f - (x + float(xs) / msaa) / (w - 1); float yscale = float(y + float(ys) / msaa) / (h - 1); if(linux) yscale = 1.0f - yscale; origin = yscale * (xscale * origin00 + (1 - xscale) * origin10) + (1 - yscale) * (xscale * origin01 + (1 - xscale) * origin11); dest = yscale * (xscale * dest00 + (1 - xscale) * dest10) + (1 - yscale) * (xscale * dest01 + (1 - xscale) * dest11); total += performRayTracing(origin, dest); } } // calculate average color total /= msaa * msaa; // result->_image result->_image[(y * result->_width + x) * 3 + 0] = total[0]; result->_image[(y * result->_width + x) * 3 + 1] = total[1]; result->_image[(y * result->_width + x) * 3 + 2] = total[2]; } } } void startRayTracing(int texIndex, bool verbose){ if(verbose) cout << "Raytracing" << endl; int w = RayTracingResolutionX; int h = RayTracingResolutionY; if(!verbose) w = previewResX; if(!verbose) h = previewResY; Image result(w, h); produceRay(0, 0, &origin00, &dest00); produceRay(0, WindowSizeX - 1, &origin01, &dest01); produceRay(WindowSizeX - 1, 0, &origin10, &dest10); produceRay(WindowSizeX - 1, WindowSizeY - 1, &origin11, &dest11); // Perform timing time_t start, end, ticks; start = clock(); // multithread #if THREADS != 0 std::thread** th = (std::thread**)alloca(numThreads * sizeof(std::thread*)); int subw = w / numThreads; for(unsigned int i = 0;i < numThreads;i++) th[i] = new std::thread(raytracePart, &result, w, h, i * subw, 0, (i + 1) * subw, h); // i * subw, 0, subw, h); // wait for them to finish for(unsigned int i = 0;i < numThreads;i++) th[i]->join(); // kill them all for(unsigned int i = 0;i < numThreads;i++) delete th[i]; #else raytracePart(&result, w, h, 0, 0, w, h); #endif // calculate elapsed time end = clock(); ticks = end - start; start = end; int millis = ticks * 1000 / CLOCKS_PER_SEC; if(verbose) printf("Rendering took %d ms cpu seconds and %d ms wall time\n", millis, millis/max(4, 1)); // write to texture glBindTexture(GL_TEXTURE_2D, textures[texIndex]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_FLOAT, &result._image[0]); // calculate elapsed time end = clock(); ticks = end - start; millis = ticks * 1000 / CLOCKS_PER_SEC; if(verbose) printf("Uploading to GPU took %d ms\n", millis); if(verbose) result.writeImage("result"); } #define VEWY_HIGH 10e6f Vec3Df black(0, 0, 0); //return the color of your pixel. Vec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest){ Ray ray = Ray(black, origin, dest); // calculate nearest triangle int idx = -1; /* the triangle that was hit */ float hit = VEWY_HIGH; /* distance to hit triangle */ unsigned int numTriangles = MyMesh.triangles.size(); for(unsigned int i = 0;i < numTriangles;i++){ float ins = ray.intersect(&MyMesh.triangles[i]); if(ins < VEWY_HIGH && ins < hit && ins > 0){ hit = ins; idx = i; } } // using black if(idx == -1) return black; Vec3Df& normal = MyMesh.triangles[idx].normal; float angle = -dot(normal, origin) * 0.33333; return (normal * 0.2f + Vec3Df(angle, angle, angle)) / 2; } void yourDebugDraw(){ //draw open gl debug stuff //this function is called every frame drawFPS(); //as an example: glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_LIGHTING); glColor3f(1, 0, 1); glBegin(GL_LINES); glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]); glVertex3f(testRayDestination[0], testRayDestination[1], testRayDestination[2]); glEnd(); glPointSize(10); glBegin(GL_POINTS); glVertex3fv(MyLightPositions[0].pointer()); glEnd(); glPopAttrib(); } void yourKeyboardFunc(char t, int x, int y){ // do what you want with the keyboard input t. // x, y are the screen position //here I use it to get the coordinates of a ray, which I then draw in the debug function. produceRay(x, y, testRayOrigin, testRayDestination); std::cout << t << " pressed! The mouse was in location " << x << "," << y << "!" << std::endl; } void drawFPS(){ clock_t diff = clock() - lastFrameTime; lastFrameTime = clock(); fps = 1 / ((float)diff / (float)CLOCKS_PER_SEC); if(framesSinceLastDraw++ > 29){ framesSinceLastDraw = 0; screenFPS = to_string((int)fps); } glLoadIdentity(); //glRasterPos2f(1.0f, 1.0f); // FPS draws on the lefthand bottom side of the screen now, if anyone knows how to get it to the lefthand top of the screen please fix it ;) for(unsigned int i = 0;i < screenFPS.length();i++){ glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, screenFPS[i]); } } <commit_msg>Refactor.<commit_after>#include "RayTracer.hpp" #include "Tree.hpp" #include <ctime> //temporary variables Vec3Df testRayOrigin; Vec3Df testRayDestination; string mesh; extern unsigned int textures[2]; clock_t lastFrameTime; float fps; unsigned int framesSinceLastDraw = 30; string screenFPS; extern unsigned int previewResX; extern unsigned int previewResY; extern unsigned int msaa; extern unsigned int numThreads; extern Tree MyTree; //use this function for any preprocessing of the mesh. int init(int argc, char **argv){ // skip program name argv[0] if present argc -= (argc > 0); argv += (argc > 0); option::Stats stats(usage, argc, argv); option::Option* options = (option::Option*)calloc(stats.options_max, sizeof(option::Option)); option::Option* buffer = (option::Option*)calloc(stats.buffer_max, sizeof(option::Option)); option::Parser parse(usage, argc, argv, options, buffer); if(parse.error()) return 1; if(options[HELP]){ int columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80; option::printUsage(fwrite, stdout, usage, columns); return 2; } lastFrameTime = clock(); if(options[MESH]){ const char* arg = options[MESH].last()->arg; if(arg != 0){ mesh = arg; } }else{ mesh = "0"; } if(mesh == "0") mesh = "cube"; else if(mesh == "1") mesh = "simple_monkey"; else if(mesh == "2") mesh = "monkey"; else if(mesh == "3") mesh = "dodgeColorTest"; mesh = string("mesh/").append(mesh).append(".obj"); MyMesh.loadMesh(mesh.c_str(), true); MyMesh.computeVertexNormals(); MyTree.build(MyMesh); //one first move: initialize the first light source //at least ONE light source has to be in the scene!!! //here, we set it to the current location of the camera MyLightPositions.push_back(MyCameraPosition); if(options[RAYTRACE]){ startRayTracing(activeTexIndex, true); return 255; } return 0; } //transformer le x, y en position 3D void produceRay(int x_I, int y_I, Vec3Df * origin, Vec3Df * dest){ int viewport[4]; double modelview[16]; double projection[16]; //point sur near plane //double positionN[3]; //point sur far plane //double positionF[3]; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); //recuperer matrices glGetDoublev(GL_PROJECTION_MATRIX, projection); //recuperer matrices glGetIntegerv(GL_VIEWPORT, viewport); //viewport int y_new = viewport[3] - y_I; double x, y, z; gluUnProject(x_I, y_new, 0, modelview, projection, viewport, &x, &y, &z); origin->p[0] = float(x); origin->p[1] = float(y); origin->p[2] = float(z); gluUnProject(x_I, y_new, 1, modelview, projection, viewport, &x, &y, &z); dest->p[0] = float(x); dest->p[1] = float(y); dest->p[2] = float(z); } void produceRay(int x_I, int y_I, Vec3Df & origin, Vec3Df & dest){ produceRay(x_I, y_I, &origin, &dest); } Vec3Df origin00, dest00; Vec3Df origin01, dest01; Vec3Df origin10, dest10; Vec3Df origin11, dest11; #ifdef WIN32 #define linux false #else #define linux true #endif void raytracePart(Image* result, int w, int h, int xx, int yy, int ww, int hh){ Vec3Df origin, dest; for(float y = yy;y < hh;y++){ for(float x = xx;x < ww;x++){ //svp, decidez vous memes quels parametres vous allez passer à la fonction //c'est le stront a la plafond, c'est drôle //e.g., maillage, triangles, sphères etc. Vec3Df total(0, 0, 0); for(unsigned int xs = 0;xs < msaa;xs++){ for(unsigned int ys = 0;ys < msaa;ys++){ float xscale = 1.0f - (x + float(xs) / msaa) / (w - 1); float yscale = float(y + float(ys) / msaa) / (h - 1); if(linux) yscale = 1.0f - yscale; origin = yscale * (xscale * origin00 + (1 - xscale) * origin10) + (1 - yscale) * (xscale * origin01 + (1 - xscale) * origin11); dest = yscale * (xscale * dest00 + (1 - xscale) * dest10) + (1 - yscale) * (xscale * dest01 + (1 - xscale) * dest11); total += performRayTracing(origin, dest); } } // calculate average color total /= msaa * msaa; // result->_image result->_image[(y * result->_width + x) * 3 + 0] = total[0]; result->_image[(y * result->_width + x) * 3 + 1] = total[1]; result->_image[(y * result->_width + x) * 3 + 2] = total[2]; } } } void startRayTracing(int texIndex, bool verbose){ if(verbose) cout << "Raytracing" << endl; int w = RayTracingResolutionX; int h = RayTracingResolutionY; if(!verbose) w = previewResX; if(!verbose) h = previewResY; Image result(w, h); produceRay(0, 0, &origin00, &dest00); produceRay(0, WindowSizeX - 1, &origin01, &dest01); produceRay(WindowSizeX - 1, 0, &origin10, &dest10); produceRay(WindowSizeX - 1, WindowSizeY - 1, &origin11, &dest11); // Perform timing time_t start, end, ticks; start = clock(); // multithread #if THREADS != 0 std::thread** th = (std::thread**)alloca(numThreads * sizeof(std::thread*)); int subw = w / numThreads; for(unsigned int i = 0;i < numThreads;i++) th[i] = new std::thread(raytracePart, &result, w, h, i * subw, 0, (i + 1) * subw, h); // i * subw, 0, subw, h); // wait for them to finish for(unsigned int i = 0;i < numThreads;i++) th[i]->join(); // kill them all for(unsigned int i = 0;i < numThreads;i++) delete th[i]; #else raytracePart(&result, w, h, 0, 0, w, h); #endif // calculate elapsed time end = clock(); ticks = end - start; start = end; int millis = ticks * 1000 / CLOCKS_PER_SEC; if(verbose) printf("Rendering took %d ms cpu seconds and %d ms wall time\n", millis, millis/max(4, 1)); // write to texture glBindTexture(GL_TEXTURE_2D, textures[texIndex]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_FLOAT, &result._image[0]); // calculate elapsed time end = clock(); ticks = end - start; millis = ticks * 1000 / CLOCKS_PER_SEC; if(verbose) printf("Uploading to GPU took %d ms\n", millis); if(verbose) result.writeImage("result"); } #define VEWY_HIGH 10e6f Vec3Df black(0, 0, 0); //return the color of your pixel. Vec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest){ Ray ray = Ray(black, origin, dest); // calculate nearest triangle int idx = -1; /* the triangle that was hit */ float hit = VEWY_HIGH; /* distance to hit triangle */ unsigned int numTriangles = MyMesh.triangles.size(); for(unsigned int i = 0;i < numTriangles;i++){ float ins = ray.intersect(&MyMesh.triangles[i]); if(ins < VEWY_HIGH && ins < hit && ins > 0){ hit = ins; idx = i; } } // using black if(idx == -1) return black; Vec3Df& normal = MyMesh.triangles[idx].normal; float angle = -dot(normal, origin) * 0.33333; return (normal * 0.2f + Vec3Df(angle, angle, angle)) / 2; } void yourDebugDraw(){ //draw open gl debug stuff //this function is called every frame drawFPS(); //as an example: glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_LIGHTING); glColor3f(1, 0, 1); glBegin(GL_LINES); glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]); glVertex3f(testRayDestination[0], testRayDestination[1], testRayDestination[2]); glEnd(); glPointSize(10); glBegin(GL_POINTS); glVertex3fv(MyLightPositions[0].pointer()); glEnd(); glPopAttrib(); } void yourKeyboardFunc(char t, int x, int y){ // do what you want with the keyboard input t. // x, y are the screen position //here I use it to get the coordinates of a ray, which I then draw in the debug function. produceRay(x, y, testRayOrigin, testRayDestination); std::cout << t << " pressed! The mouse was in location " << x << "," << y << "!" << std::endl; } void drawFPS(){ clock_t diff = clock() - lastFrameTime; lastFrameTime = clock(); fps = 1 / ((float)diff / (float)CLOCKS_PER_SEC); if(framesSinceLastDraw++ > 29){ framesSinceLastDraw = 0; screenFPS = to_string((int)fps); } glLoadIdentity(); //glRasterPos2f(1.0f, 1.0f); // FPS draws on the lefthand bottom side of the screen now, if anyone knows how to get it to the lefthand top of the screen please fix it ;) for(unsigned int i = 0;i < screenFPS.length();i++){ glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, screenFPS[i]); } } <|endoftext|>
<commit_before>#include "ucfb_reader.hpp" #include <stdexcept> Ucfb_reader::Ucfb_reader(const gsl::span<const std::byte> bytes) : _mn{reinterpret_span_as<Magic_number>( gsl::span<const std::byte, sizeof(Magic_number)>{&bytes[0], sizeof(Magic_number)})}, _size{reinterpret_span_as<std::uint32_t>( gsl::span<const std::byte, sizeof(std::uint32_t)>{&bytes[4], sizeof(std::uint32_t)})}, _data{&bytes[8]} { Expects((bytes.size() >= 8)); if (_size > static_cast<std::size_t>(bytes.size() - 8)) { throw std::runtime_error{ "Size of supplied memory is less than size of supposed chunk."}; } } Ucfb_reader::Ucfb_reader(const Magic_number mn, const std::uint32_t size, const std::byte* const data) : _mn{mn}, _size{size}, _data{data} { } Ucfb_reader Ucfb_reader::read_child(const bool unaligned) { const auto child_mn = read_trivial<Magic_number>(); const auto child_size = read_trivial<std::uint32_t>(); const auto child_data_offset = _head; _head += child_size; check_head(); if (!unaligned) align_head(); return Ucfb_reader{child_mn, child_size, _data + child_data_offset}; } auto Ucfb_reader::read_child(const std::nothrow_t, const bool unaligned) noexcept -> std::optional<Ucfb_reader> { if ((_head + 8) > _size) return std::nullopt; const auto old_head = _head; const auto child_mn = read_trivial<Magic_number>(); const auto child_size = read_trivial<std::uint32_t>(); const auto child_data_offset = _head; _head += child_size; if (_head > _size) { _head = old_head; return std::nullopt; } if (!unaligned) align_head(); return Ucfb_reader{child_mn, child_size, _data + child_data_offset}; } Ucfb_reader Ucfb_reader::read_child_strict(const Magic_number child_mn, const bool unaligned) { const auto old_head = _head; const auto child = read_child(unaligned); if (child.magic_number() != child_mn) { _head = old_head; throw std::runtime_error{"Chunk magic number mistmatch" " when performing strict read of child chunk."}; } return child; } auto Ucfb_reader::read_child_strict_optional(const Magic_number child_mn, const bool unaligned) -> std::optional<Ucfb_reader> { const auto old_head = _head; const auto child = read_child(unaligned); if (child.magic_number() != child_mn) { _head = old_head; return {}; } return child; } void Ucfb_reader::consume(const std::size_t amount, const bool unaligned) { _head += amount; check_head(); if (!unaligned) align_head(); } Ucfb_reader::operator bool() const noexcept { return (_head < _size); } void Ucfb_reader::reset_head() noexcept { _head = 0; } Magic_number Ucfb_reader::magic_number() const noexcept { return _mn; } std::size_t Ucfb_reader::size() const noexcept { return _size; } void Ucfb_reader::check_head() { if (_head > _size) { throw std::runtime_error{"Attempt to read past end of chunk."}; } } <commit_msg>fix empty .lvl files crashing<commit_after>#include "ucfb_reader.hpp" #include <stdexcept> Ucfb_reader::Ucfb_reader(const gsl::span<const std::byte> bytes) { if (bytes.size() < 8) { throw std::runtime_error{"Size of data is too small."}; } _mn = reinterpret_span_as<Magic_number>( gsl::span<const std::byte, sizeof(Magic_number)>{&bytes[0], sizeof(Magic_number)}); _size = reinterpret_span_as<std::uint32_t>( gsl::span<const std::byte, sizeof(std::uint32_t)>{&bytes[4], sizeof(std::uint32_t)}); _data = bytes.data() + 8; if (_size > static_cast<std::size_t>(bytes.size() - 8)) { throw std::runtime_error{ "Size of supplied memory is less than size of supposed chunk."}; } } Ucfb_reader::Ucfb_reader(const Magic_number mn, const std::uint32_t size, const std::byte* const data) : _mn{mn}, _size{size}, _data{data} { } Ucfb_reader Ucfb_reader::read_child(const bool unaligned) { const auto child_mn = read_trivial<Magic_number>(); const auto child_size = read_trivial<std::uint32_t>(); const auto child_data_offset = _head; _head += child_size; check_head(); if (!unaligned) align_head(); return Ucfb_reader{child_mn, child_size, _data + child_data_offset}; } auto Ucfb_reader::read_child(const std::nothrow_t, const bool unaligned) noexcept -> std::optional<Ucfb_reader> { if ((_head + 8) > _size) return std::nullopt; const auto old_head = _head; const auto child_mn = read_trivial<Magic_number>(); const auto child_size = read_trivial<std::uint32_t>(); const auto child_data_offset = _head; _head += child_size; if (_head > _size) { _head = old_head; return std::nullopt; } if (!unaligned) align_head(); return Ucfb_reader{child_mn, child_size, _data + child_data_offset}; } Ucfb_reader Ucfb_reader::read_child_strict(const Magic_number child_mn, const bool unaligned) { const auto old_head = _head; const auto child = read_child(unaligned); if (child.magic_number() != child_mn) { _head = old_head; throw std::runtime_error{"Chunk magic number mistmatch" " when performing strict read of child chunk."}; } return child; } auto Ucfb_reader::read_child_strict_optional(const Magic_number child_mn, const bool unaligned) -> std::optional<Ucfb_reader> { const auto old_head = _head; const auto child = read_child(unaligned); if (child.magic_number() != child_mn) { _head = old_head; return {}; } return child; } void Ucfb_reader::consume(const std::size_t amount, const bool unaligned) { _head += amount; check_head(); if (!unaligned) align_head(); } Ucfb_reader::operator bool() const noexcept { return (_head < _size); } void Ucfb_reader::reset_head() noexcept { _head = 0; } Magic_number Ucfb_reader::magic_number() const noexcept { return _mn; } std::size_t Ucfb_reader::size() const noexcept { return _size; } void Ucfb_reader::check_head() { if (_head > _size) { throw std::runtime_error{"Attempt to read past end of chunk."}; } } <|endoftext|>
<commit_before>#include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <string> #include "out.hpp" Rout::Rout() {} Rout::Rout(const string &filename) { file = filename; } void Rout::truncate(const string &filename) { int out; out = open(filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666); dup2(out, STDOUT_FILENO); } void Rout::append(const string &filename) { int out; out = open(filename.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666); dup2(out, STDOUT_FILENO); } bool Rout::execute(const vector<string> &cmds, const char &flag ) { if (flag == 'a') { append(file); } else { truncate(file); } char* args[512]; unsigned i; for (i = 0; i < cmds.size(); i++) { args[i] = (char*)cmds[i].c_str(); } args[i] = NULL; pid_t pid; pid = fork(); int status; if (pid == -1) { perror("fork"); exit(1); } if (pid == 0) // child process { if (execvp(args[0], args) == -1) { perror("exec"); //exit(1); } exit(1); } else // parent process { if (waitpid(pid, &status, 0) == -1) { perror("wait"); exit(1); } if (WEXITSTATUS(status) != 0) { return false; } close(out); } return true; } <commit_msg>changed out<commit_after>#include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <string> #include "out.hpp" Rout::Rout() {} Rout::Rout(const string &filename) { file = filename; int out; } void Rout::truncate(const string &filename) { out = open(filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666); dup2(out, STDOUT_FILENO); } void Rout::append(const string &filename) { int out; out = open(filename.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666); dup2(out, STDOUT_FILENO); } bool Rout::execute(const vector<string> &cmds, const char &flag ) { if (flag == 'a') { append(file); } else { truncate(file); } char* args[512]; unsigned i; for (i = 0; i < cmds.size(); i++) { args[i] = (char*)cmds[i].c_str(); } args[i] = NULL; pid_t pid; pid = fork(); int status; if (pid == -1) { perror("fork"); exit(1); } if (pid == 0) // child process { if (execvp(args[0], args) == -1) { perror("exec"); //exit(1); } exit(1); } else // parent process { if (waitpid(pid, &status, 0) == -1) { perror("wait"); exit(1); } if (WEXITSTATUS(status) != 0) { return false; } close(out); } return true; } <|endoftext|>
<commit_before>#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "FireSimulator.h" #include "../World.h" #include "../BlockID.h" #include "../Defines.h" #include "../Chunk.h" // Easy switch for turning on debugging logging: #if 0 #define FLOG LOGD #else #define FLOG(...) #endif #define MAX_CHANCE_REPLACE_FUEL 100000 #define MAX_CHANCE_FLAMMABILITY 100000 static const struct { int x, y, z; } gCrossCoords[] = { { 1, 0, 0}, {-1, 0, 0}, { 0, 0, 1}, { 0, 0, -1}, } ; static const struct { int x, y, z; } gNeighborCoords[] = { { 1, 0, 0}, {-1, 0, 0}, { 0, 1, 0}, { 0, -1, 0}, { 0, 0, 1}, { 0, 0, -1}, } ; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cFireSimulator: cFireSimulator::cFireSimulator(cWorld & a_World, cIniFile & a_IniFile) : cSimulator(a_World) { // Read params from the ini file: m_BurnStepTimeFuel = a_IniFile.GetValueSetI("FireSimulator", "BurnStepTimeFuel", 500); m_BurnStepTimeNonfuel = a_IniFile.GetValueSetI("FireSimulator", "BurnStepTimeNonfuel", 100); m_Flammability = a_IniFile.GetValueSetI("FireSimulator", "Flammability", 50); m_ReplaceFuelChance = a_IniFile.GetValueSetI("FireSimulator", "ReplaceFuelChance", 50000); } cFireSimulator::~cFireSimulator() { } void cFireSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk) { cCoordWithIntList & Data = a_Chunk->GetFireSimulatorData(); int NumMSecs = (int)a_Dt; for (cCoordWithIntList::iterator itr = Data.begin(); itr != Data.end();) { int idx = cChunkDef::MakeIndexNoCheck(itr->x, itr->y, itr->z); BLOCKTYPE BlockType = a_Chunk->GetBlock(idx); if (!IsAllowedBlock(BlockType)) { // The block is no longer eligible (not a fire block anymore; a player probably placed a block over the fire) FLOG("FS: Removing block {%d, %d, %d}", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); itr = Data.erase(itr); continue; } // Try to spread the fire: TrySpreadFire(a_Chunk, itr->x, itr->y, itr->z); itr->Data -= NumMSecs; if (itr->Data >= 0) { // Not yet, wait for it longer ++itr; continue; } // Burn out the fire one step by increasing the meta: /* FLOG("FS: Fire at {%d, %d, %d} is stepping", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); */ NIBBLETYPE BlockMeta = a_Chunk->GetMeta(idx); if (BlockMeta == 0x0f) { // The fire burnt out completely FLOG("FS: Fire at {%d, %d, %d} burnt out, removing the fire block", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); a_Chunk->SetBlock(itr->x, itr->y, itr->z, E_BLOCK_AIR, 0); RemoveFuelNeighbors(a_Chunk, itr->x, itr->y, itr->z); itr = Data.erase(itr); continue; } if((itr->y > 0) && (!DoesBurnForever(a_Chunk->GetBlock(itr->x, itr->y - 1, itr->z)))) { a_Chunk->SetMeta(idx, BlockMeta + 1); } itr->Data = GetBurnStepTime(a_Chunk, itr->x, itr->y, itr->z); // TODO: Add some randomness into this } // for itr - Data[] } bool cFireSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType) { return (a_BlockType == E_BLOCK_FIRE); } bool cFireSimulator::IsFuel(BLOCKTYPE a_BlockType) { switch (a_BlockType) { case E_BLOCK_PLANKS: case E_BLOCK_DOUBLE_WOODEN_SLAB: case E_BLOCK_WOODEN_SLAB: case E_BLOCK_WOODEN_STAIRS: case E_BLOCK_SPRUCE_WOOD_STAIRS: case E_BLOCK_BIRCH_WOOD_STAIRS: case E_BLOCK_JUNGLE_WOOD_STAIRS: case E_BLOCK_LEAVES: case E_BLOCK_NEW_LEAVES: case E_BLOCK_LOG: case E_BLOCK_NEW_LOG: case E_BLOCK_WOOL: case E_BLOCK_BOOKCASE: case E_BLOCK_FENCE: case E_BLOCK_TNT: case E_BLOCK_VINES: case E_BLOCK_HAY_BALE: case E_BLOCK_TALL_GRASS: case E_BLOCK_BIG_FLOWER: case E_BLOCK_DANDELION: case E_BLOCK_FLOWER: case E_BLOCK_CARPET: { return true; } } return false; } bool cFireSimulator::DoesBurnForever(BLOCKTYPE a_BlockType) { return (a_BlockType == E_BLOCK_NETHERRACK); } void cFireSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { if ((a_Chunk == NULL) || !a_Chunk->IsValid()) { return; } int RelX = a_BlockX - a_Chunk->GetPosX() * cChunkDef::Width; int RelZ = a_BlockZ - a_Chunk->GetPosZ() * cChunkDef::Width; BLOCKTYPE BlockType = a_Chunk->GetBlock(RelX, a_BlockY, RelZ); if (!IsAllowedBlock(BlockType)) { return; } // Check for duplicates: cFireSimulatorChunkData & ChunkData = a_Chunk->GetFireSimulatorData(); for (cCoordWithIntList::iterator itr = ChunkData.begin(), end = ChunkData.end(); itr != end; ++itr) { if ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ)) { // Already present, skip adding return; } } // for itr - ChunkData[] FLOG("FS: Adding block {%d, %d, %d}", a_BlockX, a_BlockY, a_BlockZ); ChunkData.push_back(cCoordWithInt(RelX, a_BlockY, RelZ, 100)); } int cFireSimulator::GetBurnStepTime(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { bool IsBlockBelowSolid = false; if (a_RelY > 0) { BLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ); if (DoesBurnForever(BlockBelow)) { // Is burning atop of netherrack, burn forever (re-check in 10 sec) return 10000; } if (IsFuel(BlockBelow)) { return m_BurnStepTimeFuel; } IsBlockBelowSolid = cBlockInfo::IsSolid(BlockBelow); } for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (a_Chunk->UnboundedRelGetBlock(a_RelX + gCrossCoords[i].x, a_RelY, a_RelZ + gCrossCoords[i].z, BlockType, BlockMeta)) { if (IsFuel(BlockType)) { return m_BurnStepTimeFuel; } } } // for i - gCrossCoords[] if (!IsBlockBelowSolid && (a_RelY >= 0)) { // Checked through everything, nothing was flammable // If block below isn't solid, we can't have fire, it would be a non-fueled fire // SetBlock just to make sure fire doesn't spawn a_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0); return 0; } return m_BurnStepTimeNonfuel; } void cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { /* if (m_World.GetTickRandomNumber(10000) > 100) { // Make the chance to spread 100x smaller return; } */ for (int x = a_RelX - 1; x <= a_RelX + 1; x++) { for (int z = a_RelZ - 1; z <= a_RelZ + 1; z++) { for (int y = a_RelY - 1; y <= a_RelY + 2; y++) // flames spread up one more block than around { // No need to check the coords for equality with the parent block, // it cannot catch fire anyway (because it's not an air block) if (m_World.GetTickRandomNumber(MAX_CHANCE_FLAMMABILITY) > m_Flammability) { continue; } // Start the fire in the neighbor {x, y, z} /* FLOG("FS: Trying to start fire at {%d, %d, %d}.", x + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width ); */ if (CanStartFireInBlock(a_Chunk, x, y, z)) { FLOG("FS: Starting new fire at {%d, %d, %d}.", x + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width ); a_Chunk->UnboundedRelSetBlock(x, y, z, E_BLOCK_FIRE, 0); } } // for y } // for z } // for x } void cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { for (size_t i = 0; i < ARRAYCOUNT(gNeighborCoords); i++) { BLOCKTYPE BlockType; int X = a_RelX + gNeighborCoords[i].x; int Z = a_RelZ + gNeighborCoords[i].z; cChunkPtr Neighbour = a_Chunk->GetRelNeighborChunkAdjustCoords(X, Z); if (Neighbour == NULL) { continue; } BlockType = Neighbour->GetBlockTypeMeta(X, a_RelY + gCrossCoords[i].y, Z); if (!IsFuel(BlockType)) { continue; } if (BlockType == E_BLOCK_TNT) { int AbsX = X + Neighbour->GetPosX() * cChunkDef::Width; int AbsZ = Z + Neighbour->GetPosZ() * cChunkDef::Width; m_World.SpawnPrimedTNT(AbsX, a_RelY + gNeighborCoords[i].y, AbsZ, 0); Neighbour->SetBlock(X, a_RelY + gNeighborCoords[i].y, Z, E_BLOCK_AIR, 0); return; } bool ShouldReplaceFuel = (m_World.GetTickRandomNumber(MAX_CHANCE_REPLACE_FUEL) < m_ReplaceFuelChance); Neighbour->SetBlock(X, a_RelY + gNeighborCoords[i].y, Z, ShouldReplaceFuel ? E_BLOCK_FIRE : E_BLOCK_AIR, 0); } // for i - Coords[] } bool cFireSimulator::CanStartFireInBlock(cChunk * a_NearChunk, int a_RelX, int a_RelY, int a_RelZ) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (!a_NearChunk->UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockType, BlockMeta)) { // The chunk is not accessible return false; } if (BlockType != E_BLOCK_AIR) { // Only an air block can be replaced by a fire block return false; } for (size_t i = 0; i < ARRAYCOUNT(gNeighborCoords); i++) { if (!a_NearChunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta)) { // Neighbor inaccessible, skip it while evaluating continue; } if (IsFuel(BlockType)) { return true; } } // for i - Coords[] return false; } <commit_msg>Fixed compile<commit_after> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "FireSimulator.h" #include "../World.h" #include "../BlockID.h" #include "../Defines.h" #include "../Chunk.h" // Easy switch for turning on debugging logging: #if 0 #define FLOG LOGD #else #define FLOG(...) #endif #define MAX_CHANCE_REPLACE_FUEL 100000 #define MAX_CHANCE_FLAMMABILITY 100000 static const struct { int x, y, z; } gCrossCoords[] = { { 1, 0, 0}, {-1, 0, 0}, { 0, 0, 1}, { 0, 0, -1}, } ; static const struct { int x, y, z; } gNeighborCoords[] = { { 1, 0, 0}, {-1, 0, 0}, { 0, 1, 0}, { 0, -1, 0}, { 0, 0, 1}, { 0, 0, -1}, } ; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cFireSimulator: cFireSimulator::cFireSimulator(cWorld & a_World, cIniFile & a_IniFile) : cSimulator(a_World) { // Read params from the ini file: m_BurnStepTimeFuel = a_IniFile.GetValueSetI("FireSimulator", "BurnStepTimeFuel", 500); m_BurnStepTimeNonfuel = a_IniFile.GetValueSetI("FireSimulator", "BurnStepTimeNonfuel", 100); m_Flammability = a_IniFile.GetValueSetI("FireSimulator", "Flammability", 50); m_ReplaceFuelChance = a_IniFile.GetValueSetI("FireSimulator", "ReplaceFuelChance", 50000); } cFireSimulator::~cFireSimulator() { } void cFireSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk) { cCoordWithIntList & Data = a_Chunk->GetFireSimulatorData(); int NumMSecs = (int)a_Dt; for (cCoordWithIntList::iterator itr = Data.begin(); itr != Data.end();) { int idx = cChunkDef::MakeIndexNoCheck(itr->x, itr->y, itr->z); BLOCKTYPE BlockType = a_Chunk->GetBlock(idx); if (!IsAllowedBlock(BlockType)) { // The block is no longer eligible (not a fire block anymore; a player probably placed a block over the fire) FLOG("FS: Removing block {%d, %d, %d}", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); itr = Data.erase(itr); continue; } // Try to spread the fire: TrySpreadFire(a_Chunk, itr->x, itr->y, itr->z); itr->Data -= NumMSecs; if (itr->Data >= 0) { // Not yet, wait for it longer ++itr; continue; } // Burn out the fire one step by increasing the meta: /* FLOG("FS: Fire at {%d, %d, %d} is stepping", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); */ NIBBLETYPE BlockMeta = a_Chunk->GetMeta(idx); if (BlockMeta == 0x0f) { // The fire burnt out completely FLOG("FS: Fire at {%d, %d, %d} burnt out, removing the fire block", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); a_Chunk->SetBlock(itr->x, itr->y, itr->z, E_BLOCK_AIR, 0); RemoveFuelNeighbors(a_Chunk, itr->x, itr->y, itr->z); itr = Data.erase(itr); continue; } if((itr->y > 0) && (!DoesBurnForever(a_Chunk->GetBlock(itr->x, itr->y - 1, itr->z)))) { a_Chunk->SetMeta(idx, BlockMeta + 1); } itr->Data = GetBurnStepTime(a_Chunk, itr->x, itr->y, itr->z); // TODO: Add some randomness into this } // for itr - Data[] } bool cFireSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType) { return (a_BlockType == E_BLOCK_FIRE); } bool cFireSimulator::IsFuel(BLOCKTYPE a_BlockType) { switch (a_BlockType) { case E_BLOCK_PLANKS: case E_BLOCK_DOUBLE_WOODEN_SLAB: case E_BLOCK_WOODEN_SLAB: case E_BLOCK_WOODEN_STAIRS: case E_BLOCK_SPRUCE_WOOD_STAIRS: case E_BLOCK_BIRCH_WOOD_STAIRS: case E_BLOCK_JUNGLE_WOOD_STAIRS: case E_BLOCK_LEAVES: case E_BLOCK_NEW_LEAVES: case E_BLOCK_LOG: case E_BLOCK_NEW_LOG: case E_BLOCK_WOOL: case E_BLOCK_BOOKCASE: case E_BLOCK_FENCE: case E_BLOCK_TNT: case E_BLOCK_VINES: case E_BLOCK_HAY_BALE: case E_BLOCK_TALL_GRASS: case E_BLOCK_BIG_FLOWER: case E_BLOCK_DANDELION: case E_BLOCK_FLOWER: case E_BLOCK_CARPET: { return true; } } return false; } bool cFireSimulator::DoesBurnForever(BLOCKTYPE a_BlockType) { return (a_BlockType == E_BLOCK_NETHERRACK); } void cFireSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { if ((a_Chunk == NULL) || !a_Chunk->IsValid()) { return; } int RelX = a_BlockX - a_Chunk->GetPosX() * cChunkDef::Width; int RelZ = a_BlockZ - a_Chunk->GetPosZ() * cChunkDef::Width; BLOCKTYPE BlockType = a_Chunk->GetBlock(RelX, a_BlockY, RelZ); if (!IsAllowedBlock(BlockType)) { return; } // Check for duplicates: cFireSimulatorChunkData & ChunkData = a_Chunk->GetFireSimulatorData(); for (cCoordWithIntList::iterator itr = ChunkData.begin(), end = ChunkData.end(); itr != end; ++itr) { if ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ)) { // Already present, skip adding return; } } // for itr - ChunkData[] FLOG("FS: Adding block {%d, %d, %d}", a_BlockX, a_BlockY, a_BlockZ); ChunkData.push_back(cCoordWithInt(RelX, a_BlockY, RelZ, 100)); } int cFireSimulator::GetBurnStepTime(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { bool IsBlockBelowSolid = false; if (a_RelY > 0) { BLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ); if (DoesBurnForever(BlockBelow)) { // Is burning atop of netherrack, burn forever (re-check in 10 sec) return 10000; } if (IsFuel(BlockBelow)) { return m_BurnStepTimeFuel; } IsBlockBelowSolid = cBlockInfo::IsSolid(BlockBelow); } for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (a_Chunk->UnboundedRelGetBlock(a_RelX + gCrossCoords[i].x, a_RelY, a_RelZ + gCrossCoords[i].z, BlockType, BlockMeta)) { if (IsFuel(BlockType)) { return m_BurnStepTimeFuel; } } } // for i - gCrossCoords[] if (!IsBlockBelowSolid && (a_RelY >= 0)) { // Checked through everything, nothing was flammable // If block below isn't solid, we can't have fire, it would be a non-fueled fire // SetBlock just to make sure fire doesn't spawn a_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0); return 0; } return m_BurnStepTimeNonfuel; } void cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { /* if (m_World.GetTickRandomNumber(10000) > 100) { // Make the chance to spread 100x smaller return; } */ for (int x = a_RelX - 1; x <= a_RelX + 1; x++) { for (int z = a_RelZ - 1; z <= a_RelZ + 1; z++) { for (int y = a_RelY - 1; y <= a_RelY + 2; y++) // flames spread up one more block than around { // No need to check the coords for equality with the parent block, // it cannot catch fire anyway (because it's not an air block) if (m_World.GetTickRandomNumber(MAX_CHANCE_FLAMMABILITY) > m_Flammability) { continue; } // Start the fire in the neighbor {x, y, z} /* FLOG("FS: Trying to start fire at {%d, %d, %d}.", x + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width ); */ if (CanStartFireInBlock(a_Chunk, x, y, z)) { FLOG("FS: Starting new fire at {%d, %d, %d}.", x + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width ); a_Chunk->UnboundedRelSetBlock(x, y, z, E_BLOCK_FIRE, 0); } } // for y } // for z } // for x } void cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { for (size_t i = 0; i < ARRAYCOUNT(gNeighborCoords); i++) { BLOCKTYPE BlockType; int X = a_RelX + gNeighborCoords[i].x; int Z = a_RelZ + gNeighborCoords[i].z; cChunkPtr Neighbour = a_Chunk->GetRelNeighborChunkAdjustCoords(X, Z); if (Neighbour == NULL) { continue; } BlockType = Neighbour->GetBlock(X, a_RelY + gCrossCoords[i].y, Z); if (!IsFuel(BlockType)) { continue; } if (BlockType == E_BLOCK_TNT) { int AbsX = X + Neighbour->GetPosX() * cChunkDef::Width; int AbsZ = Z + Neighbour->GetPosZ() * cChunkDef::Width; m_World.SpawnPrimedTNT(AbsX, a_RelY + gNeighborCoords[i].y, AbsZ, 0); Neighbour->SetBlock(X, a_RelY + gNeighborCoords[i].y, Z, E_BLOCK_AIR, 0); return; } bool ShouldReplaceFuel = (m_World.GetTickRandomNumber(MAX_CHANCE_REPLACE_FUEL) < m_ReplaceFuelChance); Neighbour->SetBlock(X, a_RelY + gNeighborCoords[i].y, Z, ShouldReplaceFuel ? E_BLOCK_FIRE : E_BLOCK_AIR, 0); } // for i - Coords[] } bool cFireSimulator::CanStartFireInBlock(cChunk * a_NearChunk, int a_RelX, int a_RelY, int a_RelZ) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (!a_NearChunk->UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockType, BlockMeta)) { // The chunk is not accessible return false; } if (BlockType != E_BLOCK_AIR) { // Only an air block can be replaced by a fire block return false; } for (size_t i = 0; i < ARRAYCOUNT(gNeighborCoords); i++) { if (!a_NearChunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta)) { // Neighbor inaccessible, skip it while evaluating continue; } if (IsFuel(BlockType)) { return true; } } // for i - Coords[] return false; } <|endoftext|>
<commit_before>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2020 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "UnitTest++/UnitTest++.h" #include <thread> #include <vector> #include <numeric> #include <array> #include <algorithm> #include <queue> #include <atomic> #include "etl/atomic.h" #include "etl/queue_spsc_atomic.h" #include "etl/buffer_descriptors.h" #if defined(ETL_TARGET_OS_WINDOWS) #include <Windows.h> #endif #define REALTIME_TEST 0 namespace { constexpr size_t BUFFER_SIZE = 16U; constexpr size_t N_BUFFERS = 4U; constexpr size_t DATA_COUNT = BUFFER_SIZE / 2; using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>; char buffers[N_BUFFERS][BUFFER_SIZE]; //*********************************** struct Receiver { void receive(BD::notification n) { pbuffer = n.get_descriptor().data(); count = n.get_count(); } void clear() { pbuffer = nullptr; count = 0U; } BD::pointer pbuffer; BD::size_type count; }; Receiver receiver; SUITE(test_buffer_descriptors) { ////************************************************************************* //TEST(test_constructor_plus_buffer) //{ // BD bd(&buffers[0][0]); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(!bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_and_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0], callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_set_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0]); // bd.set_callback(callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} //************************************************************************* TEST(test_buffers) { BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); } } // // //************************************************************************* // TEST(test_buffers_with_allocate_fill) // { // std::array<char, BUFFER_SIZE> test = // { // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF) // }; // // BD bd(&buffers[0][0]); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(char(0xFF)); // // CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_notifications) // { // std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 }; // // std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U); // // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // // BD bd(&buffers[0][0], callback); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // // CHECK(desc.is_valid()); // // std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data()); // bd.notify(BD::notification(desc, DATA_COUNT)); // desc.release(); // // CHECK_EQUAL(DATA_COUNT, receiver.count); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer)); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_allocate_overflow) // { // BD bd(&buffers[0][0]); // // // Use up all of the descriptors. // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // CHECK(desc.is_valid()); // } // // BD::descriptor desc = bd.allocate(); // CHECK(!desc.is_valid()); // } // // //************************************************************************* // TEST(test_allocate_release_rollover) // { // std::queue<BD::descriptor> desc_queue; // // BD bd(&buffers[0][0]); // // // Use up all of the descriptors, then release/allocate for the rest. // for (size_t i = 0U; i < (N_BUFFERS * 2); ++i) // { // BD::descriptor desc = bd.allocate(); // desc_queue.push(desc); // // CHECK(desc.is_valid()); // // if (i >= (N_BUFFERS - 1)) // { // desc_queue.front().release(); // desc_queue.pop(); // } // } // } // // //************************************************************************* // TEST(test_descriptors) // { // BD bd(&buffers[0][0]); // // BD::descriptor desc1 = bd.allocate(); // BD::descriptor desc2 = bd.allocate(); // BD::descriptor desc3 = bd.allocate(); // BD::descriptor desc4 = bd.allocate(); // // CHECK(desc1.is_allocated()); // CHECK(desc2.is_allocated()); // CHECK(desc3.is_allocated()); // CHECK(desc4.is_allocated()); // // CHECK(desc1.data() == &buffers[0][0]); // CHECK(desc2.data() == &buffers[1][0]); // CHECK(desc3.data() == &buffers[2][0]); // CHECK(desc4.data() == &buffers[3][0]); // // CHECK(desc1.max_size() == BUFFER_SIZE); // CHECK(desc2.max_size() == BUFFER_SIZE); // CHECK(desc3.max_size() == BUFFER_SIZE); // CHECK(desc4.max_size() == BUFFER_SIZE); // // CHECK(desc1.MAX_SIZE == BUFFER_SIZE); // CHECK(desc2.MAX_SIZE == BUFFER_SIZE); // CHECK(desc3.MAX_SIZE == BUFFER_SIZE); // CHECK(desc4.MAX_SIZE == BUFFER_SIZE); // // CHECK(desc1.is_valid()); // CHECK(desc2.is_valid()); // CHECK(desc3.is_valid()); // CHECK(desc4.is_valid()); // // desc1.release(); // desc2.release(); // desc3.release(); // desc4.release(); // // CHECK(desc1.is_released()); // CHECK(desc2.is_released()); // CHECK(desc3.is_released()); // CHECK(desc4.is_released()); // } // // //************************************************************************* //#if REALTIME_TEST // //#if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported //#define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) //#define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1) //#define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2) //#else //#define RAISE_THREAD_PRIORITY //#define FIX_PROCESSOR_AFFINITY1 //#define FIX_PROCESSOR_AFFINITY2 //#endif // // std::atomic_bool start = false; // // //********************************* // struct Notification // { // BD::descriptor desc; // BD::size_type count; // }; // // constexpr int N_ITERATIONS = 1000000; // // etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue; // // //********************************* // void Callback(BD::notification n) // { // desc_queue.push(n); // } // // //********************************* // void Producer() // { // static char buffers[N_BUFFERS][BUFFER_SIZE]; // // BD bd(&buffers[0][0], BD::callback_type::create<Callback>()); // // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY1; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS; ++i) // { // BD::descriptor desc; // // // Wait until we can allocate a descriptor. // do // { // desc = bd.allocate(); // } while (desc.is_valid() == false); // // if (!desc.is_allocated()) // { // ++errors; // } // // // Send a notification to the callback function. // bd.notify(BD::notification(desc, BUFFER_SIZE)); // } // // CHECK_EQUAL(0, errors); // } // // //********************************* // void Consumer() // { // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY2; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS;) // { // BD::notification notification; // // // Try to get a notification from the queue. // if (desc_queue.pop(notification)) // { // CHECK_EQUAL(BUFFER_SIZE, notification.get_count()); // CHECK(notification.get_descriptor().is_allocated()); // // if (!notification.get_descriptor().is_allocated()) // { // ++errors; // } // // notification.get_descriptor().release(); // ++i; // } // // CHECK_EQUAL(0, errors); // } // } // // //********************************* // TEST(test_multi_thread) // { // std::thread t1(Producer); // std::thread t2(Consumer); // // start = true; // // t1.join(); // t2.join(); // } //#endif }; } <commit_msg>Refactor buffer_descriptors test<commit_after>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2020 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "UnitTest++/UnitTest++.h" #include <thread> #include <vector> #include <numeric> #include <array> #include <algorithm> #include <queue> #include <atomic> #include "etl/atomic.h" #include "etl/queue_spsc_atomic.h" #include "etl/buffer_descriptors.h" #if defined(ETL_TARGET_OS_WINDOWS) #include <Windows.h> #endif #define REALTIME_TEST 0 namespace { constexpr size_t BUFFER_SIZE = 16U; constexpr size_t N_BUFFERS = 4U; constexpr size_t DATA_COUNT = BUFFER_SIZE / 2; using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>; char buffers[N_BUFFERS][BUFFER_SIZE]; //*********************************** struct Receiver { void receive(BD::notification n) { pbuffer = n.get_descriptor().data(); count = n.get_count(); } void clear() { pbuffer = nullptr; count = 0U; } BD::pointer pbuffer; BD::size_type count; }; Receiver receiver; SUITE(test_buffer_descriptors) { ////************************************************************************* //TEST(test_constructor_plus_buffer) //{ // BD bd(&buffers[0][0]); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(!bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_and_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0], callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_set_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0]); // bd.set_callback(callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} //************************************************************************* TEST(test_buffers) { BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); //CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); //CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); } } // // //************************************************************************* // TEST(test_buffers_with_allocate_fill) // { // std::array<char, BUFFER_SIZE> test = // { // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF) // }; // // BD bd(&buffers[0][0]); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(char(0xFF)); // // CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_notifications) // { // std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 }; // // std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U); // // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // // BD bd(&buffers[0][0], callback); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // // CHECK(desc.is_valid()); // // std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data()); // bd.notify(BD::notification(desc, DATA_COUNT)); // desc.release(); // // CHECK_EQUAL(DATA_COUNT, receiver.count); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer)); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_allocate_overflow) // { // BD bd(&buffers[0][0]); // // // Use up all of the descriptors. // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // CHECK(desc.is_valid()); // } // // BD::descriptor desc = bd.allocate(); // CHECK(!desc.is_valid()); // } // // //************************************************************************* // TEST(test_allocate_release_rollover) // { // std::queue<BD::descriptor> desc_queue; // // BD bd(&buffers[0][0]); // // // Use up all of the descriptors, then release/allocate for the rest. // for (size_t i = 0U; i < (N_BUFFERS * 2); ++i) // { // BD::descriptor desc = bd.allocate(); // desc_queue.push(desc); // // CHECK(desc.is_valid()); // // if (i >= (N_BUFFERS - 1)) // { // desc_queue.front().release(); // desc_queue.pop(); // } // } // } // // //************************************************************************* // TEST(test_descriptors) // { // BD bd(&buffers[0][0]); // // BD::descriptor desc1 = bd.allocate(); // BD::descriptor desc2 = bd.allocate(); // BD::descriptor desc3 = bd.allocate(); // BD::descriptor desc4 = bd.allocate(); // // CHECK(desc1.is_allocated()); // CHECK(desc2.is_allocated()); // CHECK(desc3.is_allocated()); // CHECK(desc4.is_allocated()); // // CHECK(desc1.data() == &buffers[0][0]); // CHECK(desc2.data() == &buffers[1][0]); // CHECK(desc3.data() == &buffers[2][0]); // CHECK(desc4.data() == &buffers[3][0]); // // CHECK(desc1.max_size() == BUFFER_SIZE); // CHECK(desc2.max_size() == BUFFER_SIZE); // CHECK(desc3.max_size() == BUFFER_SIZE); // CHECK(desc4.max_size() == BUFFER_SIZE); // // CHECK(desc1.MAX_SIZE == BUFFER_SIZE); // CHECK(desc2.MAX_SIZE == BUFFER_SIZE); // CHECK(desc3.MAX_SIZE == BUFFER_SIZE); // CHECK(desc4.MAX_SIZE == BUFFER_SIZE); // // CHECK(desc1.is_valid()); // CHECK(desc2.is_valid()); // CHECK(desc3.is_valid()); // CHECK(desc4.is_valid()); // // desc1.release(); // desc2.release(); // desc3.release(); // desc4.release(); // // CHECK(desc1.is_released()); // CHECK(desc2.is_released()); // CHECK(desc3.is_released()); // CHECK(desc4.is_released()); // } // // //************************************************************************* //#if REALTIME_TEST // //#if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported //#define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) //#define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1) //#define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2) //#else //#define RAISE_THREAD_PRIORITY //#define FIX_PROCESSOR_AFFINITY1 //#define FIX_PROCESSOR_AFFINITY2 //#endif // // std::atomic_bool start = false; // // //********************************* // struct Notification // { // BD::descriptor desc; // BD::size_type count; // }; // // constexpr int N_ITERATIONS = 1000000; // // etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue; // // //********************************* // void Callback(BD::notification n) // { // desc_queue.push(n); // } // // //********************************* // void Producer() // { // static char buffers[N_BUFFERS][BUFFER_SIZE]; // // BD bd(&buffers[0][0], BD::callback_type::create<Callback>()); // // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY1; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS; ++i) // { // BD::descriptor desc; // // // Wait until we can allocate a descriptor. // do // { // desc = bd.allocate(); // } while (desc.is_valid() == false); // // if (!desc.is_allocated()) // { // ++errors; // } // // // Send a notification to the callback function. // bd.notify(BD::notification(desc, BUFFER_SIZE)); // } // // CHECK_EQUAL(0, errors); // } // // //********************************* // void Consumer() // { // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY2; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS;) // { // BD::notification notification; // // // Try to get a notification from the queue. // if (desc_queue.pop(notification)) // { // CHECK_EQUAL(BUFFER_SIZE, notification.get_count()); // CHECK(notification.get_descriptor().is_allocated()); // // if (!notification.get_descriptor().is_allocated()) // { // ++errors; // } // // notification.get_descriptor().release(); // ++i; // } // // CHECK_EQUAL(0, errors); // } // } // // //********************************* // TEST(test_multi_thread) // { // std::thread t1(Producer); // std::thread t2(Consumer); // // start = true; // // t1.join(); // t2.join(); // } //#endif }; } <|endoftext|>
<commit_before>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2020 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "UnitTest++/UnitTest++.h" #include <thread> #include <vector> #include <numeric> #include <array> #include <algorithm> #include <queue> #include <atomic> #include "etl/atomic.h" #include "etl/queue_spsc_atomic.h" #include "etl/buffer_descriptors.h" #if defined(ETL_TARGET_OS_WINDOWS) #include <Windows.h> #endif #define REALTIME_TEST 0 namespace { constexpr size_t BUFFER_SIZE = 16U; constexpr size_t N_BUFFERS = 4U; constexpr size_t DATA_COUNT = BUFFER_SIZE / 2; using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>; char buffers[N_BUFFERS][BUFFER_SIZE]; //*********************************** struct Receiver { void receive(BD::notification n) { pbuffer = n.get_descriptor().data(); count = n.get_count(); } void clear() { pbuffer = nullptr; count = 0U; } BD::pointer pbuffer; BD::size_type count; }; Receiver receiver; SUITE(test_buffer_descriptors) { //************************************************************************* TEST(test_constructor_plus_buffer) { BD bd(&buffers[0][0]); CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); CHECK(!bd.is_valid()); } //************************************************************************* TEST(test_constructor_plus_buffer_and_callback) { receiver.clear(); BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); BD bd(&buffers[0][0], callback); CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); CHECK(bd.is_valid()); } //************************************************************************* TEST(test_constructor_plus_buffer_set_callback) { receiver.clear(); BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); BD bd(&buffers[0][0]); bd.set_callback(callback); CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); CHECK(bd.is_valid()); } //************************************************************************* TEST(test_buffers) { BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK(desc.is_valid()); CHECK(desc.is_allocated()); CHECK(!desc.is_released()); CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); } } //************************************************************************* TEST(test_buffers_with_allocate_fill) { std::array<char, BUFFER_SIZE> test = { char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF) }; BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(char(0xFF)); CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); } } //************************************************************************* TEST(test_notifications) { std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 }; std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U); receiver.clear(); BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); BD bd(&buffers[0][0], callback); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK(desc.is_valid()); std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data()); bd.notify(BD::notification(desc, DATA_COUNT)); desc.release(); CHECK_EQUAL(DATA_COUNT, receiver.count); CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer)); CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); } } //************************************************************************* TEST(test_allocate_overflow) { BD bd(&buffers[0][0]); // Use up all of the descriptors. for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK(desc.is_valid()); } BD::descriptor desc = bd.allocate(); CHECK(!desc.is_valid()); } //************************************************************************* TEST(test_allocate_release_rollover) { std::queue<BD::descriptor> desc_queue; BD bd(&buffers[0][0]); // Use up all of the descriptors, then release/allocate for the rest. for (size_t i = 0U; i < (N_BUFFERS * 2); ++i) { BD::descriptor desc = bd.allocate(); desc_queue.push(desc); CHECK(desc.is_valid()); if (i >= (N_BUFFERS - 1)) { desc_queue.front().release(); desc_queue.pop(); } } } //************************************************************************* TEST(test_descriptors) { BD bd(&buffers[0][0]); BD::descriptor desc1 = bd.allocate(); BD::descriptor desc2 = bd.allocate(); BD::descriptor desc3 = bd.allocate(); BD::descriptor desc4 = bd.allocate(); CHECK(desc1.is_allocated()); CHECK(desc2.is_allocated()); CHECK(desc3.is_allocated()); CHECK(desc4.is_allocated()); CHECK(desc1.data() == &buffers[0][0]); CHECK(desc2.data() == &buffers[1][0]); CHECK(desc3.data() == &buffers[2][0]); CHECK(desc4.data() == &buffers[3][0]); CHECK(desc1.max_size() == BUFFER_SIZE); CHECK(desc2.max_size() == BUFFER_SIZE); CHECK(desc3.max_size() == BUFFER_SIZE); CHECK(desc4.max_size() == BUFFER_SIZE); CHECK(desc1.MAX_SIZE == BUFFER_SIZE); CHECK(desc2.MAX_SIZE == BUFFER_SIZE); CHECK(desc3.MAX_SIZE == BUFFER_SIZE); CHECK(desc4.MAX_SIZE == BUFFER_SIZE); CHECK(desc1.is_valid()); CHECK(desc2.is_valid()); CHECK(desc3.is_valid()); CHECK(desc4.is_valid()); desc1.release(); desc2.release(); desc3.release(); desc4.release(); CHECK(desc1.is_released()); CHECK(desc2.is_released()); CHECK(desc3.is_released()); CHECK(desc4.is_released()); } //************************************************************************* #if REALTIME_TEST #if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported #define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) #define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1) #define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2) #else #define RAISE_THREAD_PRIORITY #define FIX_PROCESSOR_AFFINITY1 #define FIX_PROCESSOR_AFFINITY2 #endif std::atomic_bool start = false; //********************************* struct Notification { BD::descriptor desc; BD::size_type count; }; constexpr int N_ITERATIONS = 1000000; etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue; //********************************* void Callback(BD::notification n) { desc_queue.push(n); } //********************************* void Producer() { static char buffers[N_BUFFERS][BUFFER_SIZE]; BD bd(&buffers[0][0], BD::callback_type::create<Callback>()); RAISE_THREAD_PRIORITY; FIX_PROCESSOR_AFFINITY1; // Wait for the start flag. while (!start); int errors = 0; for (int i = 0; i < N_ITERATIONS; ++i) { BD::descriptor desc; // Wait until we can allocate a descriptor. do { desc = bd.allocate(); } while (desc.is_valid() == false); if (!desc.is_allocated()) { ++errors; } // Send a notification to the callback function. bd.notify(BD::notification(desc, BUFFER_SIZE)); } CHECK_EQUAL(0, errors); } //********************************* void Consumer() { RAISE_THREAD_PRIORITY; FIX_PROCESSOR_AFFINITY2; // Wait for the start flag. while (!start); int errors = 0; for (int i = 0; i < N_ITERATIONS;) { BD::notification notification; // Try to get a notification from the queue. if (desc_queue.pop(notification)) { CHECK_EQUAL(BUFFER_SIZE, notification.get_count()); CHECK(notification.get_descriptor().is_allocated()); if (!notification.get_descriptor().is_allocated()) { ++errors; } notification.get_descriptor().release(); ++i; } CHECK_EQUAL(0, errors); } } //********************************* TEST(test_multi_thread) { std::thread t1(Producer); std::thread t2(Consumer); start = true; t1.join(); t2.join(); } #endif }; } <commit_msg>Fixed non-initialisation of in_use flag.<commit_after>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2020 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "UnitTest++/UnitTest++.h" #include <thread> #include <vector> #include <numeric> #include <array> #include <algorithm> #include <queue> #include <atomic> #include "etl/atomic.h" #include "etl/queue_spsc_atomic.h" #include "etl/buffer_descriptors.h" #if defined(ETL_TARGET_OS_WINDOWS) #include <Windows.h> #endif #define REALTIME_TEST 0 namespace { constexpr size_t BUFFER_SIZE = 16U; constexpr size_t N_BUFFERS = 4U; constexpr size_t DATA_COUNT = BUFFER_SIZE / 2; using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>; char buffers[N_BUFFERS][BUFFER_SIZE]; //*********************************** struct Receiver { void receive(BD::notification n) { pbuffer = n.get_descriptor().data(); count = n.get_count(); } void clear() { pbuffer = nullptr; count = 0U; } BD::pointer pbuffer; BD::size_type count; }; Receiver receiver; SUITE(test_buffer_descriptors) { //************************************************************************* TEST(test_constructor_plus_buffer) { BD bd(&buffers[0][0]); CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); CHECK(!bd.is_valid()); } //************************************************************************* TEST(test_constructor_plus_buffer_and_callback) { receiver.clear(); BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); BD bd(&buffers[0][0], callback); CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); CHECK(bd.is_valid()); } //************************************************************************* TEST(test_constructor_plus_buffer_set_callback) { receiver.clear(); BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); BD bd(&buffers[0][0]); bd.set_callback(callback); CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); CHECK(bd.is_valid()); } //************************************************************************* TEST(test_buffers) { BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK(desc.is_valid()); CHECK(desc.is_allocated()); CHECK(!desc.is_released()); CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); } } //************************************************************************* TEST(test_clear) { BD bd(&buffers[0][0]); BD::descriptor desc[4]; for (size_t i = 0U; i < N_BUFFERS; ++i) { desc[i] = bd.allocate(); } bd.clear(); for (size_t i = 0U; i < N_BUFFERS; ++i) { CHECK(desc[i].is_valid()); CHECK(!desc[i].is_allocated()); CHECK(desc[i].is_released()); } } //************************************************************************* TEST(test_buffers_with_allocate_fill) { std::array<char, BUFFER_SIZE> test = { char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF) }; BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(char(0xFF)); CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); } } //************************************************************************* TEST(test_notifications) { std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 }; std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U); receiver.clear(); BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); BD bd(&buffers[0][0], callback); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK(desc.is_valid()); std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data()); bd.notify(BD::notification(desc, DATA_COUNT)); desc.release(); CHECK_EQUAL(DATA_COUNT, receiver.count); CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer)); CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); } } //************************************************************************* TEST(test_allocate_overflow) { BD bd(&buffers[0][0]); // Use up all of the descriptors. for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK(desc.is_valid()); } BD::descriptor desc = bd.allocate(); CHECK(!desc.is_valid()); } //************************************************************************* TEST(test_allocate_release_rollover) { std::queue<BD::descriptor> desc_queue; BD bd(&buffers[0][0]); // Use up all of the descriptors, then release/allocate for the rest. for (size_t i = 0U; i < (N_BUFFERS * 2); ++i) { BD::descriptor desc = bd.allocate(); desc_queue.push(desc); CHECK(desc.is_valid()); if (i >= (N_BUFFERS - 1)) { desc_queue.front().release(); desc_queue.pop(); } } } //************************************************************************* TEST(test_descriptors) { BD bd(&buffers[0][0]); BD::descriptor desc1 = bd.allocate(); BD::descriptor desc2 = bd.allocate(); BD::descriptor desc3 = bd.allocate(); BD::descriptor desc4 = bd.allocate(); CHECK(desc1.is_allocated()); CHECK(desc2.is_allocated()); CHECK(desc3.is_allocated()); CHECK(desc4.is_allocated()); CHECK(desc1.data() == &buffers[0][0]); CHECK(desc2.data() == &buffers[1][0]); CHECK(desc3.data() == &buffers[2][0]); CHECK(desc4.data() == &buffers[3][0]); CHECK(desc1.max_size() == BUFFER_SIZE); CHECK(desc2.max_size() == BUFFER_SIZE); CHECK(desc3.max_size() == BUFFER_SIZE); CHECK(desc4.max_size() == BUFFER_SIZE); CHECK(desc1.MAX_SIZE == BUFFER_SIZE); CHECK(desc2.MAX_SIZE == BUFFER_SIZE); CHECK(desc3.MAX_SIZE == BUFFER_SIZE); CHECK(desc4.MAX_SIZE == BUFFER_SIZE); CHECK(desc1.is_valid()); CHECK(desc2.is_valid()); CHECK(desc3.is_valid()); CHECK(desc4.is_valid()); desc1.release(); desc2.release(); desc3.release(); desc4.release(); CHECK(desc1.is_released()); CHECK(desc2.is_released()); CHECK(desc3.is_released()); CHECK(desc4.is_released()); } //************************************************************************* #if REALTIME_TEST #if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported #define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) #define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1) #define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2) #else #define RAISE_THREAD_PRIORITY #define FIX_PROCESSOR_AFFINITY1 #define FIX_PROCESSOR_AFFINITY2 #endif std::atomic_bool start = false; //********************************* struct Notification { BD::descriptor desc; BD::size_type count; }; constexpr int N_ITERATIONS = 1000000; etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue; //********************************* void Callback(BD::notification n) { desc_queue.push(n); } //********************************* void Producer() { static char buffers[N_BUFFERS][BUFFER_SIZE]; BD bd(&buffers[0][0], BD::callback_type::create<Callback>()); RAISE_THREAD_PRIORITY; FIX_PROCESSOR_AFFINITY1; // Wait for the start flag. while (!start); int errors = 0; for (int i = 0; i < N_ITERATIONS; ++i) { BD::descriptor desc; // Wait until we can allocate a descriptor. do { desc = bd.allocate(); } while (desc.is_valid() == false); if (!desc.is_allocated()) { ++errors; } // Send a notification to the callback function. bd.notify(BD::notification(desc, BUFFER_SIZE)); } CHECK_EQUAL(0, errors); } //********************************* void Consumer() { RAISE_THREAD_PRIORITY; FIX_PROCESSOR_AFFINITY2; // Wait for the start flag. while (!start); int errors = 0; for (int i = 0; i < N_ITERATIONS;) { BD::notification notification; // Try to get a notification from the queue. if (desc_queue.pop(notification)) { CHECK_EQUAL(BUFFER_SIZE, notification.get_count()); CHECK(notification.get_descriptor().is_allocated()); if (!notification.get_descriptor().is_allocated()) { ++errors; } notification.get_descriptor().release(); ++i; } CHECK_EQUAL(0, errors); } } //********************************* TEST(test_multi_thread) { std::thread t1(Producer); std::thread t2(Consumer); start = true; t1.join(); t2.join(); } #endif }; } <|endoftext|>
<commit_before>/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. * * All rights reserved. Email: [email protected] Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * 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 files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ // TriMesh code by Erwin de Vries. #include <ode/collision.h> #include <ode/matrix.h> #include <ode/rotation.h> #include <ode/odemath.h> #include "collision_util.h" #define TRIMESH_INTERNAL #include "collision_trimesh_internal.h" // Trimesh data dxTriMeshData::dxTriMeshData(){ #ifndef dTRIMESH_ENABLED dUASSERT(g, "dTRIMESH_ENABLED is not defined. Trimesh geoms will not work"); #endif } dxTriMeshData::~dxTriMeshData(){ // } void dxTriMeshData::Build(const void* Vertices, int VertexStide, int VertexCount, const void* Indices, int IndexCount, int TriStride, bool Single){ Mesh.SetNbTriangles(IndexCount / 3); Mesh.SetNbVertices(VertexCount); Mesh.SetPointers((IndexedTriangle*)Indices, (Point*)Vertices); Mesh.SetStrides(TriStride, VertexStide); Mesh.Single = Single; // Build tree BuildSettings Settings; Settings.mRules = SPLIT_BEST_AXIS; OPCODECREATE TreeBuilder; TreeBuilder.mIMesh = &Mesh; TreeBuilder.mSettings = Settings; TreeBuilder.mNoLeaf = true; TreeBuilder.mQuantized = false; TreeBuilder.mKeepOriginal = false; TreeBuilder.mCanRemap = false; BVTree.Build(TreeBuilder); } dTriMeshDataID dGeomTriMeshDataCreate(){ return new dxTriMeshData(); } void dGeomTriMeshDataDestroy(dTriMeshDataID g){ delete g; } void dGeomTriMeshDataBuildSingle(dTriMeshDataID g, const void* Vertices, int VertexStride, int VertexCount, const void* Indices, int IndexCount, int TriStride){ dUASSERT(g, "argument not trimesh data"); g->Build(Vertices, VertexStride, VertexCount, Indices, IndexCount, TriStride, true); } void dGeomTriMeshDataBuildDouble(dTriMeshDataID g, const void* Vertices, int VertexStride, int VertexCount, const void* Indices, int IndexCount, int TriStride){ dUASSERT(g, "argument not trimesh data"); g->Build(Vertices, VertexStride, VertexCount, Indices, IndexCount, TriStride, false); } void dGeomTriMeshDataBuildSimple(dTriMeshDataID g, const dReal* Vertices, int VertexCount, const int* Indices, int IndexCount){ #ifdef dSINGLE dGeomTriMeshDataBuildSingle(g, Vertices, 4 * sizeof(dReal), VertexCount, Indices, IndexCount, 3 * sizeof(unsigned int)); #else dGeomTriMeshDataBuildDouble(g, Vertices, 4 * sizeof(dReal), VertexCount, Indices, IndexCount, 3 * sizeof(unsigned int)); #endif } // Trimesh PlanesCollider dxTriMesh::_PlanesCollider; SphereCollider dxTriMesh::_SphereCollider; OBBCollider dxTriMesh::_OBBCollider; RayCollider dxTriMesh::_RayCollider; AABBTreeCollider dxTriMesh::_AABBTreeCollider; CollisionFaces dxTriMesh::Faces; dxTriMesh::dxTriMesh(dSpaceID Space, dTriMeshDataID Data) : dxGeom(Space, 1){ type = dTriMeshClass; this->Data = Data; _RayCollider.SetDestination(&Faces); _PlanesCollider.SetTemporalCoherence(true); _SphereCollider.SetTemporalCoherence(true); _OBBCollider.SetTemporalCoherence(true); _AABBTreeCollider.SetTemporalCoherence(true); _SphereCollider.SetPrimitiveTests(false); } dxTriMesh::~dxTriMesh(){ // } void dxTriMesh::ClearTCCache(){ SphereTCCache.setSize(0); BoxTCCache.setSize(0); } int dxTriMesh::AABBTest(dxGeom* g, dReal aabb[6]){ return 1; } void dxTriMesh::computeAABB(){ aabb[0] = -dInfinity; aabb[1] = dInfinity; aabb[2] = -dInfinity; aabb[3] = dInfinity; aabb[4] = -dInfinity; aabb[5] = dInfinity; } dGeomID dCreateTriMesh(dSpaceID space, dTriMeshDataID Data, dTriCallback* Callback, dTriArrayCallback* ArrayCallback, dTriRayCallback* RayCallback){ dxTriMesh* Geom = new dxTriMesh(space, Data); Geom->Callback = Callback; Geom->ArrayCallback = ArrayCallback; Geom->RayCallback = RayCallback; return Geom; } void dGeomTriMeshClearTC(dGeomID g){ dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh"); dxTriMesh* Geom = (dxTriMesh*)g; Geom->ClearTCCache(); } // Getting data void dGeomTriMeshGetTriangle(dGeomID g, int Index, dVector3* v0, dVector3* v1, dVector3* v2){ dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh"); dxTriMesh* Geom = (dxTriMesh*)g; const dVector3& Position = *(const dVector3*)dGeomGetPosition(g); const dMatrix3& Rotation = *(const dMatrix3*)dGeomGetRotation(g); dVector3 v[3]; FetchTriangle(Geom, Index, Rotation, Position, v); if (v0){ (*v0)[0] = v[0][0]; (*v0)[1] = v[0][1]; (*v0)[2] = v[0][2]; (*v0)[3] = v[0][3]; } if (v1){ (*v1)[0] = v[1][0]; (*v1)[1] = v[1][1]; (*v1)[2] = v[1][2]; (*v1)[3] = v[0][3]; } if (v2){ (*v2)[0] = v[2][0]; (*v2)[1] = v[2][1]; (*v2)[2] = v[2][2]; (*v2)[3] = v[2][3]; } } void dGeomTriMeshGetPoint(dGeomID g, int Index, dReal u, dReal v, dVector3 Out){ dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh"); dxTriMesh* Geom = (dxTriMesh*)g; const dVector3& Position = *(const dVector3*)dGeomGetPosition(g); const dMatrix3& Rotation = *(const dMatrix3*)dGeomGetRotation(g); dVector3 dv[3]; FetchTriangle(Geom, Index, Rotation, Position, dv); GetPointFromBarycentric(dv, u, v, Out); } <commit_msg>apply the following fix, with a mildly descriptive comment: ------------------ Hi,<commit_after>/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. * * All rights reserved. Email: [email protected] Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * 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 files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ // TriMesh code by Erwin de Vries. #include <ode/collision.h> #include <ode/matrix.h> #include <ode/rotation.h> #include <ode/odemath.h> #include "collision_util.h" #define TRIMESH_INTERNAL #include "collision_trimesh_internal.h" // Trimesh data dxTriMeshData::dxTriMeshData(){ #ifndef dTRIMESH_ENABLED dUASSERT(g, "dTRIMESH_ENABLED is not defined. Trimesh geoms will not work"); #endif } dxTriMeshData::~dxTriMeshData(){ // } void dxTriMeshData::Build(const void* Vertices, int VertexStide, int VertexCount, const void* Indices, int IndexCount, int TriStride, bool Single){ Mesh.SetNbTriangles(IndexCount / 3); Mesh.SetNbVertices(VertexCount); Mesh.SetPointers((IndexedTriangle*)Indices, (Point*)Vertices); Mesh.SetStrides(TriStride, VertexStide); Mesh.Single = Single; // Build tree BuildSettings Settings; Settings.mRules = SPLIT_BEST_AXIS; OPCODECREATE TreeBuilder; TreeBuilder.mIMesh = &Mesh; TreeBuilder.mSettings = Settings; TreeBuilder.mNoLeaf = true; TreeBuilder.mQuantized = false; TreeBuilder.mKeepOriginal = false; TreeBuilder.mCanRemap = false; BVTree.Build(TreeBuilder); } dTriMeshDataID dGeomTriMeshDataCreate(){ return new dxTriMeshData(); } void dGeomTriMeshDataDestroy(dTriMeshDataID g){ delete g; } void dGeomTriMeshDataBuildSingle(dTriMeshDataID g, const void* Vertices, int VertexStride, int VertexCount, const void* Indices, int IndexCount, int TriStride){ dUASSERT(g, "argument not trimesh data"); g->Build(Vertices, VertexStride, VertexCount, Indices, IndexCount, TriStride, true); } void dGeomTriMeshDataBuildDouble(dTriMeshDataID g, const void* Vertices, int VertexStride, int VertexCount, const void* Indices, int IndexCount, int TriStride){ dUASSERT(g, "argument not trimesh data"); g->Build(Vertices, VertexStride, VertexCount, Indices, IndexCount, TriStride, false); } void dGeomTriMeshDataBuildSimple(dTriMeshDataID g, const dReal* Vertices, int VertexCount, const int* Indices, int IndexCount){ #ifdef dSINGLE dGeomTriMeshDataBuildSingle(g, Vertices, 4 * sizeof(dReal), VertexCount, Indices, IndexCount, 3 * sizeof(unsigned int)); #else dGeomTriMeshDataBuildDouble(g, Vertices, 4 * sizeof(dReal), VertexCount, Indices, IndexCount, 3 * sizeof(unsigned int)); #endif } // Trimesh PlanesCollider dxTriMesh::_PlanesCollider; SphereCollider dxTriMesh::_SphereCollider; OBBCollider dxTriMesh::_OBBCollider; RayCollider dxTriMesh::_RayCollider; AABBTreeCollider dxTriMesh::_AABBTreeCollider; CollisionFaces dxTriMesh::Faces; dxTriMesh::dxTriMesh(dSpaceID Space, dTriMeshDataID Data) : dxGeom(Space, 1){ type = dTriMeshClass; this->Data = Data; _RayCollider.SetDestination(&Faces); _PlanesCollider.SetTemporalCoherence(true); _SphereCollider.SetTemporalCoherence(true); _OBBCollider.SetTemporalCoherence(true); _AABBTreeCollider.SetTemporalCoherence(true); _SphereCollider.SetPrimitiveTests(false); } dxTriMesh::~dxTriMesh(){ // } void dxTriMesh::ClearTCCache(){ /* dxTriMesh::ClearTCCache uses dArray's setSize(0) to clear the caches - but the destructor isn't called when doing this, so we would leak. So, call the previous caches' containers' destructors by hand first. */ int i, n; n = SphereTCCache.size(); for( i = 0; i < n; ++i ) { SphereTCCache[i].~SphereTC(); } SphereTCCache.setSize(0); n = BoxTCCache.size(); for( i = 0; i < n; ++i ) { BoxTCCache[i].~BoxTC(); } BoxTCCache.setSize(0); } int dxTriMesh::AABBTest(dxGeom* g, dReal aabb[6]){ return 1; } void dxTriMesh::computeAABB(){ aabb[0] = -dInfinity; aabb[1] = dInfinity; aabb[2] = -dInfinity; aabb[3] = dInfinity; aabb[4] = -dInfinity; aabb[5] = dInfinity; } dGeomID dCreateTriMesh(dSpaceID space, dTriMeshDataID Data, dTriCallback* Callback, dTriArrayCallback* ArrayCallback, dTriRayCallback* RayCallback){ dxTriMesh* Geom = new dxTriMesh(space, Data); Geom->Callback = Callback; Geom->ArrayCallback = ArrayCallback; Geom->RayCallback = RayCallback; return Geom; } void dGeomTriMeshClearTC(dGeomID g){ dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh"); dxTriMesh* Geom = (dxTriMesh*)g; Geom->ClearTCCache(); } // Getting data void dGeomTriMeshGetTriangle(dGeomID g, int Index, dVector3* v0, dVector3* v1, dVector3* v2){ dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh"); dxTriMesh* Geom = (dxTriMesh*)g; const dVector3& Position = *(const dVector3*)dGeomGetPosition(g); const dMatrix3& Rotation = *(const dMatrix3*)dGeomGetRotation(g); dVector3 v[3]; FetchTriangle(Geom, Index, Rotation, Position, v); if (v0){ (*v0)[0] = v[0][0]; (*v0)[1] = v[0][1]; (*v0)[2] = v[0][2]; (*v0)[3] = v[0][3]; } if (v1){ (*v1)[0] = v[1][0]; (*v1)[1] = v[1][1]; (*v1)[2] = v[1][2]; (*v1)[3] = v[0][3]; } if (v2){ (*v2)[0] = v[2][0]; (*v2)[1] = v[2][1]; (*v2)[2] = v[2][2]; (*v2)[3] = v[2][3]; } } void dGeomTriMeshGetPoint(dGeomID g, int Index, dReal u, dReal v, dVector3 Out){ dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh"); dxTriMesh* Geom = (dxTriMesh*)g; const dVector3& Position = *(const dVector3*)dGeomGetPosition(g); const dMatrix3& Rotation = *(const dMatrix3*)dGeomGetRotation(g); dVector3 dv[3]; FetchTriangle(Geom, Index, Rotation, Position, dv); GetPointFromBarycentric(dv, u, v, Out); } <|endoftext|>
<commit_before><commit_msg>reorganize alias<commit_after><|endoftext|>
<commit_before>/* This file is part of the Cagibi daemon. Copyright 2010-2011 Friedrich W. H. Kossebau <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "upnpproxy.h" // program #include "upnpproxydbusadaptor.h" #include "ssdpwatcher.h" #include "rootdevice.h" #include "device.h" // Qt #include <QtCore/QTimer> #include <QtCore/QSettings> #include <QtCore/QDebug> namespace Cagibi { static const int defaultShutDownTimeout = CAGIBI_DAEMON_SHUTDOWN_SECS; static const int defaultSearchTimeout = CAGIBI_DAEMON_SEARCH_TIMEOUT_SECS; static void fillMap( DeviceTypeMap& map, const Device& device ) { map.insert( device.udn(), device.type() ); foreach( const Cagibi::Device& subDevice, device.devices() ) fillMap( map, subDevice ); } static void fillMapByType( DeviceTypeMap& map, const Device& device, const QString& type ) { const QString deviceType = device.type(); if( deviceType == type ) map.insert( device.udn(), deviceType ); foreach( const Cagibi::Device& subDevice, device.devices() ) fillMapByType( map, subDevice, type ); } static const Device* find( const Device& device, const QString& udn ) { const Device* result = 0; if( device.udn() == udn ) result = &device; else { foreach( const Cagibi::Device& subDevice, device.devices() ) { result = find( subDevice, udn ); if( result ) break; } } return result; } UPnPProxy::UPnPProxy( QObject* parent ) : QObject( parent ), mSsdpWatcher( new SSDPWatcher(this) ) { QSettings::setPath( QSettings::NativeFormat, QSettings::SystemScope, QLatin1String(SYSCONF_INSTALL_DIR) ); QSettings settings( QSettings::SystemScope, QLatin1String("cagibid") ); mShutDownTimeout = settings.value( QLatin1String("ShutDownTimeout"), defaultShutDownTimeout ).toInt(); const int searchTimeout = settings.value( QLatin1String("SearchTimeout"), defaultSearchTimeout ).toInt(); // setup timer to shutdown on no UPnP activity mShutDownTimer = new QTimer( this ); mShutDownTimer->setInterval( mShutDownTimeout * 1000 ); // in msec mShutDownTimer->setSingleShot( true ); connect( mShutDownTimer, SIGNAL(timeout()), SLOT(shutDown()) ); // publish service on D-Bus new UPnPProxyDBusAdaptor( this ); QDBusConnection dBusConnection = QDBusConnection::systemBus(); dBusConnection.registerService( QLatin1String("org.kde.Cagibi") ); dBusConnection.registerObject( QLatin1String("/org/kde/Cagibi"), this ); // install listener to UPnP changes connect( mSsdpWatcher, SIGNAL(deviceDiscovered( Cagibi::RootDevice* )), SLOT(onDeviceDiscovered( Cagibi::RootDevice* )) ); connect( mSsdpWatcher, SIGNAL(deviceRemoved( Cagibi::RootDevice* )), SLOT(onDeviceRemoved( Cagibi::RootDevice* )) ); connect( mSsdpWatcher, SIGNAL(initialSearchCompleted()), SLOT(onInitialSearchCompleted()) ); mSsdpWatcher->startDiscover( searchTimeout ); } DeviceTypeMap UPnPProxy::allDevices() const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); fillMap( result, device ); } // being used, so reset the shutdown timer if active if( mShutDownTimer->isActive() ) mShutDownTimer->start(); return result; } DeviceTypeMap UPnPProxy::devicesByParent( const QString& udn ) const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); if( udn.isEmpty() ) result.insert( device.udn(), device.type() ); else { const Device* match = find( device, udn ); if( match ) { foreach( const Cagibi::Device& subDevice, device.devices() ) result.insert( subDevice.udn(), subDevice.type() ); break; } } } // being used, so reset the shutdown timer if active if( mShutDownTimer->isActive() ) mShutDownTimer->start(); return result; } DeviceTypeMap UPnPProxy::devicesByType( const QString& type ) const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); fillMapByType( result, device, type ); } return result; } Device UPnPProxy::deviceDetails( const QString& udn ) const { Device result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); const Device* match = find( device, udn ); if( match ) { result = *match; break; } } return result; } void UPnPProxy::shutDown() { qApp->quit(); } void UPnPProxy::onInitialSearchCompleted() { if( shutsDownOnNoActivity() && mSsdpWatcher->devicesCount() == 0 ) mShutDownTimer->start(); } void UPnPProxy::onDeviceDiscovered( RootDevice* rootDevice ) { DeviceTypeMap devices; const Device device = rootDevice->device(); fillMap( devices, device ); mShutDownTimer->stop(); emit devicesAdded( devices ); } void UPnPProxy::onDeviceRemoved( RootDevice* rootDevice ) { DeviceTypeMap devices; const Device device = rootDevice->device(); fillMap( devices, device ); if( shutsDownOnNoActivity() && mSsdpWatcher->devicesCount() == 0 ) mShutDownTimer->start(); emit devicesRemoved( devices ); } UPnPProxy::~UPnPProxy() { } } <commit_msg>Changed: on shutdown signal all existing devices as removed<commit_after>/* This file is part of the Cagibi daemon. Copyright 2010-2011 Friedrich W. H. Kossebau <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "upnpproxy.h" // program #include "upnpproxydbusadaptor.h" #include "ssdpwatcher.h" #include "rootdevice.h" #include "device.h" // Qt #include <QtCore/QTimer> #include <QtCore/QSettings> #include <QtCore/QDebug> namespace Cagibi { static const int defaultShutDownTimeout = CAGIBI_DAEMON_SHUTDOWN_SECS; static const int defaultSearchTimeout = CAGIBI_DAEMON_SEARCH_TIMEOUT_SECS; static void fillMap( DeviceTypeMap& map, const Device& device ) { map.insert( device.udn(), device.type() ); foreach( const Cagibi::Device& subDevice, device.devices() ) fillMap( map, subDevice ); } static void fillMapByType( DeviceTypeMap& map, const Device& device, const QString& type ) { const QString deviceType = device.type(); if( deviceType == type ) map.insert( device.udn(), deviceType ); foreach( const Cagibi::Device& subDevice, device.devices() ) fillMapByType( map, subDevice, type ); } static const Device* find( const Device& device, const QString& udn ) { const Device* result = 0; if( device.udn() == udn ) result = &device; else { foreach( const Cagibi::Device& subDevice, device.devices() ) { result = find( subDevice, udn ); if( result ) break; } } return result; } UPnPProxy::UPnPProxy( QObject* parent ) : QObject( parent ), mSsdpWatcher( new SSDPWatcher(this) ) { QSettings::setPath( QSettings::NativeFormat, QSettings::SystemScope, QLatin1String(SYSCONF_INSTALL_DIR) ); QSettings settings( QSettings::SystemScope, QLatin1String("cagibid") ); mShutDownTimeout = settings.value( QLatin1String("ShutDownTimeout"), defaultShutDownTimeout ).toInt(); const int searchTimeout = settings.value( QLatin1String("SearchTimeout"), defaultSearchTimeout ).toInt(); // setup timer to shutdown on no UPnP activity mShutDownTimer = new QTimer( this ); mShutDownTimer->setInterval( mShutDownTimeout * 1000 ); // in msec mShutDownTimer->setSingleShot( true ); connect( mShutDownTimer, SIGNAL(timeout()), SLOT(shutDown()) ); // publish service on D-Bus new UPnPProxyDBusAdaptor( this ); QDBusConnection dBusConnection = QDBusConnection::systemBus(); dBusConnection.registerService( QLatin1String("org.kde.Cagibi") ); dBusConnection.registerObject( QLatin1String("/org/kde/Cagibi"), this ); // install listener to UPnP changes connect( mSsdpWatcher, SIGNAL(deviceDiscovered( Cagibi::RootDevice* )), SLOT(onDeviceDiscovered( Cagibi::RootDevice* )) ); connect( mSsdpWatcher, SIGNAL(deviceRemoved( Cagibi::RootDevice* )), SLOT(onDeviceRemoved( Cagibi::RootDevice* )) ); connect( mSsdpWatcher, SIGNAL(initialSearchCompleted()), SLOT(onInitialSearchCompleted()) ); mSsdpWatcher->startDiscover( searchTimeout ); } DeviceTypeMap UPnPProxy::allDevices() const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); fillMap( result, device ); } // being used, so reset the shutdown timer if active if( mShutDownTimer->isActive() ) mShutDownTimer->start(); return result; } DeviceTypeMap UPnPProxy::devicesByParent( const QString& udn ) const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); if( udn.isEmpty() ) result.insert( device.udn(), device.type() ); else { const Device* match = find( device, udn ); if( match ) { foreach( const Cagibi::Device& subDevice, device.devices() ) result.insert( subDevice.udn(), subDevice.type() ); break; } } } // being used, so reset the shutdown timer if active if( mShutDownTimer->isActive() ) mShutDownTimer->start(); return result; } DeviceTypeMap UPnPProxy::devicesByType( const QString& type ) const { DeviceTypeMap result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); fillMapByType( result, device, type ); } return result; } Device UPnPProxy::deviceDetails( const QString& udn ) const { Device result; const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) { const Device device = rootDevice->device(); const Device* match = find( device, udn ); if( match ) { result = *match; break; } } return result; } void UPnPProxy::shutDown() { qApp->quit(); } void UPnPProxy::onInitialSearchCompleted() { if( shutsDownOnNoActivity() && mSsdpWatcher->devicesCount() == 0 ) mShutDownTimer->start(); } void UPnPProxy::onDeviceDiscovered( RootDevice* rootDevice ) { DeviceTypeMap devices; const Device device = rootDevice->device(); fillMap( devices, device ); mShutDownTimer->stop(); emit devicesAdded( devices ); } void UPnPProxy::onDeviceRemoved( RootDevice* rootDevice ) { DeviceTypeMap devices; const Device device = rootDevice->device(); fillMap( devices, device ); if( shutsDownOnNoActivity() && mSsdpWatcher->devicesCount() == 0 ) mShutDownTimer->start(); emit devicesRemoved( devices ); } UPnPProxy::~UPnPProxy() { // simulate that all devices are removed const QList<RootDevice*> rootDevices = mSsdpWatcher->devices(); foreach( RootDevice* rootDevice, rootDevices ) onDeviceRemoved( rootDevice ); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __CPU_EXEC_CONTEXT_HH__ #define __CPU_EXEC_CONTEXT_HH__ #include "config/full_system.hh" #include "mem/mem_req.hh" #include "sim/faults.hh" #include "sim/host.hh" #include "sim/serialize.hh" #include "sim/byteswap.hh" // forward declaration: see functional_memory.hh // @todo: Figure out a more architecture independent way to obtain the ITB and // DTB pointers. class AlphaDTB; class AlphaITB; class BaseCPU; class Event; class FunctionalMemory; class PhysicalMemory; class Process; class System; class ExecContext { protected: typedef TheISA::RegFile RegFile; typedef TheISA::MachInst MachInst; typedef TheISA::IntReg IntReg; typedef TheISA::MiscRegFile MiscRegFile; typedef TheISA::MiscReg MiscReg; public: enum Status { /// Initialized but not running yet. All CPUs start in /// this state, but most transition to Active on cycle 1. /// In MP or SMT systems, non-primary contexts will stay /// in this state until a thread is assigned to them. Unallocated, /// Running. Instructions should be executed only when /// the context is in this state. Active, /// Temporarily inactive. Entered while waiting for /// synchronization, etc. Suspended, /// Permanently shut down. Entered when target executes /// m5exit pseudo-instruction. When all contexts enter /// this state, the simulation will terminate. Halted }; virtual ~ExecContext() { }; virtual BaseCPU *getCpuPtr() = 0; virtual void setCpuId(int id) = 0; virtual int readCpuId() = 0; virtual FunctionalMemory *getMemPtr() = 0; #if FULL_SYSTEM virtual System *getSystemPtr() = 0; virtual PhysicalMemory *getPhysMemPtr() = 0; virtual AlphaITB *getITBPtr() = 0; virtual AlphaDTB * getDTBPtr() = 0; #else virtual Process *getProcessPtr() = 0; #endif virtual Status status() const = 0; virtual void setStatus(Status new_status) = 0; /// Set the status to Active. Optional delay indicates number of /// cycles to wait before beginning execution. virtual void activate(int delay = 1) = 0; /// Set the status to Suspended. virtual void suspend() = 0; /// Set the status to Unallocated. virtual void deallocate() = 0; /// Set the status to Halted. virtual void halt() = 0; #if FULL_SYSTEM virtual void dumpFuncProfile() = 0; #endif virtual void takeOverFrom(ExecContext *old_context) = 0; virtual void regStats(const std::string &name) = 0; virtual void serialize(std::ostream &os) = 0; virtual void unserialize(Checkpoint *cp, const std::string &section) = 0; #if FULL_SYSTEM virtual Event *getQuiesceEvent() = 0; // Not necessarily the best location for these... // Having an extra function just to read these is obnoxious virtual Tick readLastActivate() = 0; virtual Tick readLastSuspend() = 0; virtual void profileClear() = 0; virtual void profileSample() = 0; #endif virtual int getThreadNum() = 0; virtual bool validInstAddr(Addr addr) = 0; virtual bool validDataAddr(Addr addr) = 0; virtual int getInstAsid() = 0; virtual int getDataAsid() = 0; virtual Fault translateInstReq(MemReqPtr &req) = 0; virtual Fault translateDataReadReq(MemReqPtr &req) = 0; virtual Fault translateDataWriteReq(MemReqPtr &req) = 0; // Also somewhat obnoxious. Really only used for the TLB fault. // However, may be quite useful in SPARC. virtual TheISA::MachInst getInst() = 0; virtual void copyArchRegs(ExecContext *xc) = 0; virtual void clearArchRegs() = 0; // // New accessors for new decoder. // virtual uint64_t readIntReg(int reg_idx) = 0; virtual float readFloatRegSingle(int reg_idx) = 0; virtual double readFloatRegDouble(int reg_idx) = 0; virtual uint64_t readFloatRegInt(int reg_idx) = 0; virtual void setIntReg(int reg_idx, uint64_t val) = 0; virtual void setFloatRegSingle(int reg_idx, float val) = 0; virtual void setFloatRegDouble(int reg_idx, double val) = 0; virtual void setFloatRegInt(int reg_idx, uint64_t val) = 0; virtual uint64_t readPC() = 0; virtual void setPC(uint64_t val) = 0; virtual uint64_t readNextPC() = 0; virtual void setNextPC(uint64_t val) = 0; virtual MiscReg readMiscReg(int misc_reg) = 0; virtual MiscReg readMiscRegWithEffect(int misc_reg, Fault &fault) = 0; virtual Fault setMiscReg(int misc_reg, const MiscReg &val) = 0; virtual Fault setMiscRegWithEffect(int misc_reg, const MiscReg &val) = 0; // Also not necessarily the best location for these two. Hopefully will go // away once we decide upon where st cond failures goes. virtual unsigned readStCondFailures() = 0; virtual void setStCondFailures(unsigned sc_failures) = 0; #if FULL_SYSTEM virtual int readIntrFlag() = 0; virtual void setIntrFlag(int val) = 0; virtual Fault hwrei() = 0; virtual bool inPalMode() = 0; virtual bool simPalCheck(int palFunc) = 0; #endif // Only really makes sense for old CPU model. Still could be useful though. virtual bool misspeculating() = 0; #if !FULL_SYSTEM virtual IntReg getSyscallArg(int i) = 0; // used to shift args for indirect syscall virtual void setSyscallArg(int i, IntReg val) = 0; virtual void setSyscallReturn(SyscallReturn return_value) = 0; virtual void syscall() = 0; // Same with st cond failures. virtual Counter readFuncExeInst() = 0; virtual void setFuncExeInst(Counter new_val) = 0; #endif }; template <class XC> class ProxyExecContext : public ExecContext { public: ProxyExecContext(XC *actual_xc) { actualXC = actual_xc; } private: XC *actualXC; public: BaseCPU *getCpuPtr() { return actualXC->getCpuPtr(); } void setCpuId(int id) { actualXC->setCpuId(id); } int readCpuId() { return actualXC->readCpuId(); } FunctionalMemory *getMemPtr() { return actualXC->getMemPtr(); } #if FULL_SYSTEM System *getSystemPtr() { return actualXC->getSystemPtr(); } PhysicalMemory *getPhysMemPtr() { return actualXC->getPhysMemPtr(); } AlphaITB *getITBPtr() { return actualXC->getITBPtr(); } AlphaDTB *getDTBPtr() { return actualXC->getDTBPtr(); } #else Process *getProcessPtr() { return actualXC->getProcessPtr(); } #endif Status status() const { return actualXC->status(); } void setStatus(Status new_status) { actualXC->setStatus(new_status); } /// Set the status to Active. Optional delay indicates number of /// cycles to wait before beginning execution. void activate(int delay = 1) { actualXC->activate(delay); } /// Set the status to Suspended. void suspend() { actualXC->suspend(); } /// Set the status to Unallocated. void deallocate() { actualXC->deallocate(); } /// Set the status to Halted. void halt() { actualXC->halt(); } #if FULL_SYSTEM void dumpFuncProfile() { actualXC->dumpFuncProfile(); } #endif void takeOverFrom(ExecContext *oldContext) { actualXC->takeOverFrom(oldContext); } void regStats(const std::string &name) { actualXC->regStats(name); } void serialize(std::ostream &os) { actualXC->serialize(os); } void unserialize(Checkpoint *cp, const std::string &section) { actualXC->unserialize(cp, section); } #if FULL_SYSTEM Event *getQuiesceEvent() { return actualXC->getQuiesceEvent(); } Tick readLastActivate() { return actualXC->readLastActivate(); } Tick readLastSuspend() { return actualXC->readLastSuspend(); } void profileClear() { return actualXC->profileClear(); } void profileSample() { return actualXC->profileSample(); } #endif int getThreadNum() { return actualXC->getThreadNum(); } bool validInstAddr(Addr addr) { return actualXC->validInstAddr(addr); } bool validDataAddr(Addr addr) { return actualXC->validDataAddr(addr); } int getInstAsid() { return actualXC->getInstAsid(); } int getDataAsid() { return actualXC->getDataAsid(); } Fault translateInstReq(MemReqPtr &req) { return actualXC->translateInstReq(req); } Fault translateDataReadReq(MemReqPtr &req) { return actualXC->translateDataReadReq(req); } Fault translateDataWriteReq(MemReqPtr &req) { return actualXC->translateDataWriteReq(req); } // @todo: Do I need this? MachInst getInst() { return actualXC->getInst(); } // @todo: Do I need this? void copyArchRegs(ExecContext *xc) { actualXC->copyArchRegs(xc); } void clearArchRegs() { actualXC->clearArchRegs(); } // // New accessors for new decoder. // uint64_t readIntReg(int reg_idx) { return actualXC->readIntReg(reg_idx); } float readFloatRegSingle(int reg_idx) { return actualXC->readFloatRegSingle(reg_idx); } double readFloatRegDouble(int reg_idx) { return actualXC->readFloatRegDouble(reg_idx); } uint64_t readFloatRegInt(int reg_idx) { return actualXC->readFloatRegInt(reg_idx); } void setIntReg(int reg_idx, uint64_t val) { actualXC->setIntReg(reg_idx, val); } void setFloatRegSingle(int reg_idx, float val) { actualXC->setFloatRegSingle(reg_idx, val); } void setFloatRegDouble(int reg_idx, double val) { actualXC->setFloatRegDouble(reg_idx, val); } void setFloatRegInt(int reg_idx, uint64_t val) { actualXC->setFloatRegInt(reg_idx, val); } uint64_t readPC() { return actualXC->readPC(); } void setPC(uint64_t val) { actualXC->setPC(val); } uint64_t readNextPC() { return actualXC->readNextPC(); } void setNextPC(uint64_t val) { actualXC->setNextPC(val); } MiscReg readMiscReg(int misc_reg) { return actualXC->readMiscReg(misc_reg); } MiscReg readMiscRegWithEffect(int misc_reg, Fault &fault) { return actualXC->readMiscRegWithEffect(misc_reg, fault); } Fault setMiscReg(int misc_reg, const MiscReg &val) { return actualXC->setMiscReg(misc_reg, val); } Fault setMiscRegWithEffect(int misc_reg, const MiscReg &val) { return actualXC->setMiscRegWithEffect(misc_reg, val); } unsigned readStCondFailures() { return actualXC->readStCondFailures(); } void setStCondFailures(unsigned sc_failures) { actualXC->setStCondFailures(sc_failures); } #if FULL_SYSTEM int readIntrFlag() { return actualXC->readIntrFlag(); } void setIntrFlag(int val) { actualXC->setIntrFlag(val); } Fault hwrei() { return actualXC->hwrei(); } bool inPalMode() { return actualXC->inPalMode(); } bool simPalCheck(int palFunc) { return actualXC->simPalCheck(palFunc); } #endif // @todo: Fix this! bool misspeculating() { return actualXC->misspeculating(); } #if !FULL_SYSTEM IntReg getSyscallArg(int i) { return actualXC->getSyscallArg(i); } // used to shift args for indirect syscall void setSyscallArg(int i, IntReg val) { actualXC->setSyscallArg(i, val); } void setSyscallReturn(SyscallReturn return_value) { actualXC->setSyscallReturn(return_value); } void syscall() { actualXC->syscall(); } Counter readFuncExeInst() { return actualXC->readFuncExeInst(); } void setFuncExeInst(Counter new_val) { return actualXC->setFuncExeInst(new_val); } #endif }; #endif <commit_msg>Remove unnecessary functions.<commit_after>/* * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __CPU_EXEC_CONTEXT_HH__ #define __CPU_EXEC_CONTEXT_HH__ #include "config/full_system.hh" #include "mem/mem_req.hh" #include "sim/faults.hh" #include "sim/host.hh" #include "sim/serialize.hh" #include "sim/byteswap.hh" // forward declaration: see functional_memory.hh // @todo: Figure out a more architecture independent way to obtain the ITB and // DTB pointers. class AlphaDTB; class AlphaITB; class BaseCPU; class Event; class FunctionalMemory; class PhysicalMemory; class Process; class System; class ExecContext { protected: typedef TheISA::RegFile RegFile; typedef TheISA::MachInst MachInst; typedef TheISA::IntReg IntReg; typedef TheISA::MiscRegFile MiscRegFile; typedef TheISA::MiscReg MiscReg; public: enum Status { /// Initialized but not running yet. All CPUs start in /// this state, but most transition to Active on cycle 1. /// In MP or SMT systems, non-primary contexts will stay /// in this state until a thread is assigned to them. Unallocated, /// Running. Instructions should be executed only when /// the context is in this state. Active, /// Temporarily inactive. Entered while waiting for /// synchronization, etc. Suspended, /// Permanently shut down. Entered when target executes /// m5exit pseudo-instruction. When all contexts enter /// this state, the simulation will terminate. Halted }; virtual ~ExecContext() { }; virtual BaseCPU *getCpuPtr() = 0; virtual void setCpuId(int id) = 0; virtual int readCpuId() = 0; virtual FunctionalMemory *getMemPtr() = 0; #if FULL_SYSTEM virtual System *getSystemPtr() = 0; virtual PhysicalMemory *getPhysMemPtr() = 0; virtual AlphaITB *getITBPtr() = 0; virtual AlphaDTB * getDTBPtr() = 0; #else virtual Process *getProcessPtr() = 0; #endif virtual Status status() const = 0; virtual void setStatus(Status new_status) = 0; /// Set the status to Active. Optional delay indicates number of /// cycles to wait before beginning execution. virtual void activate(int delay = 1) = 0; /// Set the status to Suspended. virtual void suspend() = 0; /// Set the status to Unallocated. virtual void deallocate() = 0; /// Set the status to Halted. virtual void halt() = 0; #if FULL_SYSTEM virtual void dumpFuncProfile() = 0; #endif virtual void takeOverFrom(ExecContext *old_context) = 0; virtual void regStats(const std::string &name) = 0; virtual void serialize(std::ostream &os) = 0; virtual void unserialize(Checkpoint *cp, const std::string &section) = 0; #if FULL_SYSTEM virtual Event *getQuiesceEvent() = 0; // Not necessarily the best location for these... // Having an extra function just to read these is obnoxious virtual Tick readLastActivate() = 0; virtual Tick readLastSuspend() = 0; virtual void profileClear() = 0; virtual void profileSample() = 0; #endif virtual int getThreadNum() = 0; // Also somewhat obnoxious. Really only used for the TLB fault. // However, may be quite useful in SPARC. virtual TheISA::MachInst getInst() = 0; virtual void copyArchRegs(ExecContext *xc) = 0; virtual void clearArchRegs() = 0; // // New accessors for new decoder. // virtual uint64_t readIntReg(int reg_idx) = 0; virtual float readFloatRegSingle(int reg_idx) = 0; virtual double readFloatRegDouble(int reg_idx) = 0; virtual uint64_t readFloatRegInt(int reg_idx) = 0; virtual void setIntReg(int reg_idx, uint64_t val) = 0; virtual void setFloatRegSingle(int reg_idx, float val) = 0; virtual void setFloatRegDouble(int reg_idx, double val) = 0; virtual void setFloatRegInt(int reg_idx, uint64_t val) = 0; virtual uint64_t readPC() = 0; virtual void setPC(uint64_t val) = 0; virtual uint64_t readNextPC() = 0; virtual void setNextPC(uint64_t val) = 0; virtual MiscReg readMiscReg(int misc_reg) = 0; virtual MiscReg readMiscRegWithEffect(int misc_reg, Fault &fault) = 0; virtual Fault setMiscReg(int misc_reg, const MiscReg &val) = 0; virtual Fault setMiscRegWithEffect(int misc_reg, const MiscReg &val) = 0; // Also not necessarily the best location for these two. Hopefully will go // away once we decide upon where st cond failures goes. virtual unsigned readStCondFailures() = 0; virtual void setStCondFailures(unsigned sc_failures) = 0; #if FULL_SYSTEM virtual bool inPalMode() = 0; #endif // Only really makes sense for old CPU model. Still could be useful though. virtual bool misspeculating() = 0; #if !FULL_SYSTEM virtual IntReg getSyscallArg(int i) = 0; // used to shift args for indirect syscall virtual void setSyscallArg(int i, IntReg val) = 0; virtual void setSyscallReturn(SyscallReturn return_value) = 0; // virtual void syscall() = 0; // Same with st cond failures. virtual Counter readFuncExeInst() = 0; #endif }; template <class XC> class ProxyExecContext : public ExecContext { public: ProxyExecContext(XC *actual_xc) { actualXC = actual_xc; } private: XC *actualXC; public: BaseCPU *getCpuPtr() { return actualXC->getCpuPtr(); } void setCpuId(int id) { actualXC->setCpuId(id); } int readCpuId() { return actualXC->readCpuId(); } FunctionalMemory *getMemPtr() { return actualXC->getMemPtr(); } #if FULL_SYSTEM System *getSystemPtr() { return actualXC->getSystemPtr(); } PhysicalMemory *getPhysMemPtr() { return actualXC->getPhysMemPtr(); } AlphaITB *getITBPtr() { return actualXC->getITBPtr(); } AlphaDTB *getDTBPtr() { return actualXC->getDTBPtr(); } #else Process *getProcessPtr() { return actualXC->getProcessPtr(); } #endif Status status() const { return actualXC->status(); } void setStatus(Status new_status) { actualXC->setStatus(new_status); } /// Set the status to Active. Optional delay indicates number of /// cycles to wait before beginning execution. void activate(int delay = 1) { actualXC->activate(delay); } /// Set the status to Suspended. void suspend() { actualXC->suspend(); } /// Set the status to Unallocated. void deallocate() { actualXC->deallocate(); } /// Set the status to Halted. void halt() { actualXC->halt(); } #if FULL_SYSTEM void dumpFuncProfile() { actualXC->dumpFuncProfile(); } #endif void takeOverFrom(ExecContext *oldContext) { actualXC->takeOverFrom(oldContext); } void regStats(const std::string &name) { actualXC->regStats(name); } void serialize(std::ostream &os) { actualXC->serialize(os); } void unserialize(Checkpoint *cp, const std::string &section) { actualXC->unserialize(cp, section); } #if FULL_SYSTEM Event *getQuiesceEvent() { return actualXC->getQuiesceEvent(); } Tick readLastActivate() { return actualXC->readLastActivate(); } Tick readLastSuspend() { return actualXC->readLastSuspend(); } void profileClear() { return actualXC->profileClear(); } void profileSample() { return actualXC->profileSample(); } #endif int getThreadNum() { return actualXC->getThreadNum(); } // @todo: Do I need this? MachInst getInst() { return actualXC->getInst(); } // @todo: Do I need this? void copyArchRegs(ExecContext *xc) { actualXC->copyArchRegs(xc); } void clearArchRegs() { actualXC->clearArchRegs(); } // // New accessors for new decoder. // uint64_t readIntReg(int reg_idx) { return actualXC->readIntReg(reg_idx); } float readFloatRegSingle(int reg_idx) { return actualXC->readFloatRegSingle(reg_idx); } double readFloatRegDouble(int reg_idx) { return actualXC->readFloatRegDouble(reg_idx); } uint64_t readFloatRegInt(int reg_idx) { return actualXC->readFloatRegInt(reg_idx); } void setIntReg(int reg_idx, uint64_t val) { actualXC->setIntReg(reg_idx, val); } void setFloatRegSingle(int reg_idx, float val) { actualXC->setFloatRegSingle(reg_idx, val); } void setFloatRegDouble(int reg_idx, double val) { actualXC->setFloatRegDouble(reg_idx, val); } void setFloatRegInt(int reg_idx, uint64_t val) { actualXC->setFloatRegInt(reg_idx, val); } uint64_t readPC() { return actualXC->readPC(); } void setPC(uint64_t val) { actualXC->setPC(val); } uint64_t readNextPC() { return actualXC->readNextPC(); } void setNextPC(uint64_t val) { actualXC->setNextPC(val); } MiscReg readMiscReg(int misc_reg) { return actualXC->readMiscReg(misc_reg); } MiscReg readMiscRegWithEffect(int misc_reg, Fault &fault) { return actualXC->readMiscRegWithEffect(misc_reg, fault); } Fault setMiscReg(int misc_reg, const MiscReg &val) { return actualXC->setMiscReg(misc_reg, val); } Fault setMiscRegWithEffect(int misc_reg, const MiscReg &val) { return actualXC->setMiscRegWithEffect(misc_reg, val); } unsigned readStCondFailures() { return actualXC->readStCondFailures(); } void setStCondFailures(unsigned sc_failures) { actualXC->setStCondFailures(sc_failures); } #if FULL_SYSTEM bool inPalMode() { return actualXC->inPalMode(); } #endif // @todo: Fix this! bool misspeculating() { return actualXC->misspeculating(); } #if !FULL_SYSTEM IntReg getSyscallArg(int i) { return actualXC->getSyscallArg(i); } // used to shift args for indirect syscall void setSyscallArg(int i, IntReg val) { actualXC->setSyscallArg(i, val); } void setSyscallReturn(SyscallReturn return_value) { actualXC->setSyscallReturn(return_value); } // void syscall() { actualXC->syscall(); } Counter readFuncExeInst() { return actualXC->readFuncExeInst(); } #endif }; #endif <|endoftext|>
<commit_before>// // nthRoot.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "nthRoot.h" using namespace std; nthRoot::nthRoot(int root, int operand, int coefficient) { this->type = "nthRoot"; this->operand = operand; this->root = root; this->coefficient = coefficient; this->simplify(); if ((root % 2) == 0 && operand < 0) { throw runtime_error("unreal answer"); } } nthRoot::nthRoot(int root, Expression* eoperand, int coefficient) { this->type = "nthRoot"; this->eoperand = eoperand; this->root = root; this->coefficient = coefficient; if ((root % 2) == 0 && eoperand->type == "integer") { Integer *a = (Integer *)eoperand; if (a->getValue() < 0) { throw runtime_error("unreal answer"); } } if ((root % 2) == 0 && eoperand->type == "Rational"){ Rational *b = (Rational*)eoperand; if ((b->getNumerator() < 0 || b->getDenominator() < 0) && !(b->getNumerator() < 0 && b->getDenominator() < 0)) { throw runtime_error("unreal answer"); } } } nthRoot::~nthRoot() { } int* nthRoot::primeFactorization(int n, int div, int k) { if (n % div == 0) { factors[k] = div; primeFactorization((n / div), div, k++); } else if (div <= n) { primeFactorization(n, div++, k); } return factors; } /*int* nthRoot::primeFactorization(int n) { //non-recursive version int k = 0; while (n%2 == 0) { factors[k] = 2; k++; n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { if (n%i == 0) { while (n%i == 0) { factors[k] = i; k++; n = n/i; } } } if (n > 1) { factors[k] = n; } return factors; // added bonus: factors should be sorted already } */ Expression* nthRoot::simplify(){ //if coefficient == 0 then return 0? //if operand < 0 throw an error if ((root % 2) == 0 && operand < 0) { throw runtime_error("unreal answer"); } // factors = this->primeFactorization(operand); copy(this->primeFactorization(operand, 2, 0), this->primeFactorization(operand, 2, 0)+50, factors); int i = 0; int factorsSize = sizeof(factors)/sizeof(factors[0]); while (i <= factorsSize) { //all this takes unnecessary factors out of the operand int j = i; //and puts them into the coefficient int count = 0; while (j <= factorsSize && factors[j + 1] == factors[j]) { count++; j++; } if (count >= root) { coefficient *= (factors[i] ^ (count/root)); operand = operand / (factors[i] ^ (count - (count % root))); } i = j + 1; } if (operand == 1) { Integer* newInt = new Integer(coefficient); return newInt; } else { Expression* newRoot = new nthRoot(root, operand, coefficient); delete this; //is this necessary? return newRoot; } } Expression* nthRoot::add(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot && operand == asOperand) { int newCoefficient = asCoefficient + coefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else { return this; } } Expression* nthRoot::subtract(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot && operand == asOperand) { int newCoefficient = coefficient - asCoefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else { return this; } } Expression* nthRoot::multiply(Expression* a) { if (a->type == "integer") { Integer *b = (Integer*)a; int asValue = b->getValue(); int newCoefficient = asValue * coefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } if (a->type == "nthRoot") { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot) { int newCoefficient = asCoefficient * coefficient; int newOperand = operand * asOperand; //asOperand doesnt exist? nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } } else { return this; } return this; } Expression* nthRoot::divide(Expression* a) { nthRoot *b = (nthRoot *)a; int asRoot = b->getRoot(); int asOperand = b->getOperand(); int asCoefficient = b->getCoefficient(); if (root == asRoot && fmod( ((double)coefficient / (double)asCoefficient), 1) == 0 && fmod(((double)operand / (double)asOperand), 1) == 0) { int newCoefficient = coefficient / asCoefficient; int newOperand = operand / asOperand; nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else if (fmod( ((double)coefficient / (double)asCoefficient),1) == 0) { int newCoefficient = coefficient / asCoefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else { return this; } } int nthRoot::getRoot() { return root; } int nthRoot::getOperand() { return operand; } int nthRoot::getCoefficient() { return coefficient; } void nthRoot::setCoefficient(int n) { this->coefficient = n; } void nthRoot::setOperand(int n) { this->operand = n; } void nthRoot::setRoot(int n) { this->root = n; } ostream& nthRoot::print(std::ostream& output) const { output << this->coefficient << "*" << this->root << "rt:" << this->operand; return output; } string nthRoot::toString() { stringstream s; s << coefficient << "*" << root << "rt:" << operand; return s.str(); } bool nthRoot::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool nthRoot::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool nthRoot::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool nthRoot::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; }<commit_msg>tried to fix primefac<commit_after>// // nthRoot.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "nthRoot.h" using namespace std; nthRoot::nthRoot(int root, int operand, int coefficient) { this->type = "nthRoot"; this->operand = operand; this->root = root; this->coefficient = coefficient; this->simplify(); if ((root % 2) == 0 && operand < 0) { throw runtime_error("unreal answer"); } } nthRoot::nthRoot(int root, Expression* eoperand, int coefficient) { this->type = "nthRoot"; this->eoperand = eoperand; this->root = root; this->coefficient = coefficient; if ((root % 2) == 0 && eoperand->type == "integer") { Integer *a = (Integer *)eoperand; if (a->getValue() < 0) { throw runtime_error("unreal answer"); } } if ((root % 2) == 0 && eoperand->type == "Rational"){ Rational *b = (Rational*)eoperand; if ((b->getNumerator() < 0 || b->getDenominator() < 0) && !(b->getNumerator() < 0 && b->getDenominator() < 0)) { throw runtime_error("unreal answer"); } } } nthRoot::~nthRoot() { } int* nthRoot::primeFactorization(int n, int div, int k) { if (n % div == 0) { factors[k] = div; if (div == n) { return factors; } else { primeFactorization((n / div), div, k++); } } else if (div <= n) { primeFactorization(n, div++, k); } return factors; } /*int* nthRoot::primeFactorization(int n) { //non-recursive version int k = 0; while (n%2 == 0) { factors[k] = 2; k++; n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { if (n%i == 0) { while (n%i == 0) { factors[k] = i; k++; n = n/i; } } } if (n > 1) { factors[k] = n; } return factors; // added bonus: factors should be sorted already } */ Expression* nthRoot::simplify(){ //if coefficient == 0 then return 0? //if operand < 0 throw an error if ((root % 2) == 0 && operand < 0) { throw runtime_error("unreal answer"); } // factors = this->primeFactorization(operand); copy(this->primeFactorization(operand, 2, 0), this->primeFactorization(operand, 2, 0)+50, factors); int i = 0; int factorsSize = sizeof(factors)/sizeof(factors[0]); while (i <= factorsSize) { //all this takes unnecessary factors out of the operand int j = i; //and puts them into the coefficient int count = 0; while (j <= factorsSize && factors[j + 1] == factors[j]) { count++; j++; } if (count >= root) { coefficient *= (factors[i] ^ (count/root)); operand = operand / (factors[i] ^ (count - (count % root))); } i = j + 1; } if (operand == 1) { Integer* newInt = new Integer(coefficient); return newInt; } else { Expression* newRoot = new nthRoot(root, operand, coefficient); delete this; //is this necessary? return newRoot; } } Expression* nthRoot::add(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot && operand == asOperand) { int newCoefficient = asCoefficient + coefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else { return this; } } Expression* nthRoot::subtract(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot && operand == asOperand) { int newCoefficient = coefficient - asCoefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else { return this; } } Expression* nthRoot::multiply(Expression* a) { if (a->type == "integer") { Integer *b = (Integer*)a; int asValue = b->getValue(); int newCoefficient = asValue * coefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } if (a->type == "nthRoot") { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot) { int newCoefficient = asCoefficient * coefficient; int newOperand = operand * asOperand; //asOperand doesnt exist? nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } } else { return this; } return this; } Expression* nthRoot::divide(Expression* a) { nthRoot *b = (nthRoot *)a; int asRoot = b->getRoot(); int asOperand = b->getOperand(); int asCoefficient = b->getCoefficient(); if (root == asRoot && fmod( ((double)coefficient / (double)asCoefficient), 1) == 0 && fmod(((double)operand / (double)asOperand), 1) == 0) { int newCoefficient = coefficient / asCoefficient; int newOperand = operand / asOperand; nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else if (fmod( ((double)coefficient / (double)asCoefficient),1) == 0) { int newCoefficient = coefficient / asCoefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else { return this; } } int nthRoot::getRoot() { return root; } int nthRoot::getOperand() { return operand; } int nthRoot::getCoefficient() { return coefficient; } void nthRoot::setCoefficient(int n) { this->coefficient = n; } void nthRoot::setOperand(int n) { this->operand = n; } void nthRoot::setRoot(int n) { this->root = n; } ostream& nthRoot::print(std::ostream& output) const { output << this->coefficient << "*" << this->root << "rt:" << this->operand; return output; } string nthRoot::toString() { stringstream s; s << coefficient << "*" << root << "rt:" << operand; return s.str(); } bool nthRoot::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool nthRoot::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool nthRoot::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool nthRoot::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } <|endoftext|>
<commit_before><commit_msg>Add empty method for thread safe queue<commit_after><|endoftext|>
<commit_before>// Copyright: 2014, Ableton AG, Berlin. All rights reserved. //! @note Turn to one to check if our custom accumulate has any //! performance cost or not. // // #define ABL_REDUCE_WITH_ACCUMULATE 1 // #define ABL_REDUCE_NON_VARIADIC 0 #include <ableton/build_system/Warnings.hpp> #include <ableton/funken/Transducers.hpp> #include <ableton/testing/Benchmark.hpp> ABL_DISABLE_WARNINGS #include <boost/range/adaptors.hpp> #include <boost/range/numeric.hpp> #include <boost/range/algorithm.hpp> #include <boost/range/algorithm_ext/iota.hpp> ABL_RESTORE_WARNINGS #include <gtest/gtest.h> namespace ableton { namespace funken { constexpr auto DATA_SIZE = 1000; constexpr auto ITERATIONS = 1000; template <typename FnT> void xformBenchmark(FnT&& fn) { auto data = std::vector<int>(DATA_SIZE); boost::iota(data, 0); for (std::size_t n = 0; n < ITERATIONS; ++n) testing::unoptimize(fn(data)); } TEST(Transduce_Benchmark, FilterMapCopy_BoostRange) { xformBenchmark( [&](const std::vector<int>& data) { using namespace boost::adaptors; auto result = std::vector<int>{}; boost::copy( data | filtered([](int x) { return x % 2 == 0; }) | transformed([](int x) { return x * 2; }), std::back_inserter(result)); return result; }); } TEST(Transduce_Benchmark, FilterMapCopy_Stl) { xformBenchmark( [&](const std::vector<int>& data) { std::vector<int> result; std::remove_copy_if( data.begin(), data.end(), std::back_inserter(result), [](int x) { return x % 2 == 0; }); std::transform( result.begin(), result.end(), result.begin(), [](int x) { return x * 2; }); return result; }); } TEST(Transduce_Benchmark, FilterMapCopy_Transduce) { xformBenchmark( [&](const std::vector<int>& data) { return into( std::vector<int>{}, comp(filter([](int x) { return x % 2 == 0; }), map([](int x) { return x * 2; })), data); }); } TEST(Transduce_Benchmark, FilterMapReduce_BoostRange) { xformBenchmark( [&](const std::vector<int>& data) { using namespace boost::adaptors; return boost::accumulate( data | filtered([](int x) { return x % 2 == 0; }) | transformed([](int x) { return x * 2; }), 0, std::plus<int>{}); }); } TEST(Transduce_Benchmark, FilterMapReduce_Stl) { xformBenchmark( [&](const std::vector<int>& data) { std::vector<int> result; std::remove_copy_if( data.begin(), data.end(), std::back_inserter(result), [](int x) { return x % 2 == 0; }); std::transform( result.begin(), result.end(), result.begin(), [](int x) { return x * 2; }); return std::accumulate( result.begin(), result.end(), 0, std::plus<int>{}); }); } TEST(Transduce_Benchmark, FilterMapReduce_Transduce) { xformBenchmark( [&](const std::vector<int>& data) { return transduce( comp(filter([](int x) { return x % 2 == 0; }), map([](int x) { return x * 2; })), std::plus<int>{}, 0, data); }); } } // namespace funken } // namespace ableton <commit_msg>funken: add transducer benchmark comparing with hand-rolled accumulate<commit_after>// Copyright: 2014, Ableton AG, Berlin. All rights reserved. //! @note Turn to one to check if our custom accumulate has any //! performance cost or not. // // #define ABL_REDUCE_WITH_ACCUMULATE 1 // #define ABL_REDUCE_NON_VARIADIC 0 #include <ableton/build_system/Warnings.hpp> #include <ableton/funken/Transducers.hpp> #include <ableton/testing/Benchmark.hpp> ABL_DISABLE_WARNINGS #include <boost/range/adaptors.hpp> #include <boost/range/numeric.hpp> #include <boost/range/algorithm.hpp> #include <boost/range/algorithm_ext/iota.hpp> ABL_RESTORE_WARNINGS #include <gtest/gtest.h> namespace ableton { namespace funken { constexpr auto DATA_SIZE = 1000; constexpr auto ITERATIONS = 1000; template <typename FnT> void xformBenchmark(FnT&& fn) { auto data = std::vector<int>(DATA_SIZE); boost::iota(data, 0); for (std::size_t n = 0; n < ITERATIONS; ++n) testing::unoptimize(fn(data)); } TEST(Transduce_Benchmark, FilterMapCopy_BoostRange) { xformBenchmark( [&](const std::vector<int>& data) { using namespace boost::adaptors; auto result = std::vector<int>{}; boost::copy( data | filtered([](int x) { return x % 2 == 0; }) | transformed([](int x) { return x * 2; }), std::back_inserter(result)); return result; }); } TEST(Transduce_Benchmark, FilterMapCopy_Stl) { xformBenchmark( [&](const std::vector<int>& data) { std::vector<int> result; std::remove_copy_if( data.begin(), data.end(), std::back_inserter(result), [](int x) { return x % 2 == 0; }); std::transform( result.begin(), result.end(), result.begin(), [](int x) { return x * 2; }); return result; }); } TEST(Transduce_Benchmark, FilterMapCopy_Transduce) { xformBenchmark( [&](const std::vector<int>& data) { return into( std::vector<int>{}, comp(filter([](int x) { return x % 2 == 0; }), map([](int x) { return x * 2; })), data); }); } TEST(Transduce_Benchmark, FilterMapReduce_BoostRange) { xformBenchmark( [&](const std::vector<int>& data) { using namespace boost::adaptors; return boost::accumulate( data | filtered([](int x) { return x % 2 == 0; }) | transformed([](int x) { return x * 2; }), 0, std::plus<int>{}); }); } TEST(Transduce_Benchmark, FilterMapReduce_Stl) { xformBenchmark( [&](const std::vector<int>& data) { std::vector<int> result; std::remove_copy_if( data.begin(), data.end(), std::back_inserter(result), [](int x) { return x % 2 == 0; }); std::transform( result.begin(), result.end(), result.begin(), [](int x) { return x * 2; }); return std::accumulate( result.begin(), result.end(), 0, std::plus<int>{}); }); } TEST(Transduce_Benchmark, FilterMapReduce_Accumulate) { xformBenchmark( [](const std::vector<int>& data) { return std::accumulate( data.begin(), data.end(), 0, [](int state, int input) { if (input % 2 == 0) { return state + input * 2; } return state; }); }); } TEST(Transduce_Benchmark, FilterMapReduce_Transduce) { xformBenchmark( [&](const std::vector<int>& data) { return transduce( comp(filter([](int x) { return x % 2 == 0; }), map([](int x) { return x * 2; })), std::plus<int>{}, 0, data); }); } } // namespace funken } // namespace ableton <|endoftext|>
<commit_before><commit_msg>-Werror,-Wunused-const-variable<commit_after><|endoftext|>
<commit_before><?hh // strict /** * @copyright 2010-2015, The Titon Project * @license http://opensource.org/licenses/bsd-license.php * @link http://titon.io */ namespace Titon\Context; use Closure; use ArrayAccess; use ReflectionClass; use ReflectionMethod; use ReflectionFunction; use ReflectionException; use Titon\Context\Definition\CallableDefinition; use Titon\Context\Definition\ClosureDefinition; use Titon\Context\Definition\ClassDefinition; use Titon\Context\Definition\Definition; use Titon\Context\Exception\AlreadyRegisteredException; /** * The depository serves as a dependency injector. After registering an object, * class, or callable with the depository, retrieving it will handle any necessary * dependency injection and reflection resolution before returning the object for * use. * * @package Titon\Context */ class Depository implements ArrayAccess { /** * Hash of registered item definitions keyed by its alias or class name * * @var array */ protected array $items = []; /** * Hash of registered, and already constructed, singletons keyed by its * alias or class name * * @var array */ protected array $singletons = []; /** * Map of aliases to registered classes and keys * * @var AliasMap */ protected AliasMap $aliases = Map{}; /** * Instantiate a new container object */ public function __construct() { $this->register('Titon\Context\Depository', $this); } /** * Register a new class, callable, or object in the container * * @param string $key The alias (container key) for the registered item * @param mixed $concrete The class name, closure, object to register in * the container, or null to use the alias as the * class name * @param bool $singleton Whether or not the container should register the * concrete as a singleton or not (only if concrete * is class name or a closure) * * @return object|$definition Either the concrete (if an object is registered) * or the definition of the registered item */ public function register(string $key, ?mixed $concrete = null, boolean $singleton = false): mixed { if (isset($this[$key]) || isset($this->aliases[$key])) { throw new AlreadyRegisteredException("Key $key has already been registered"); } if (is_null($concrete)) { $concrete = $key; } if (is_object($concrete) && !($concrete instanceof Closure)) { if ($key !== get_class($concrete)) { $this->aliases[$key] = get_class($concrete); $key = get_class($concrete); } $this->singletons[$key] = $concrete; return $concrete; } if (is_string($concrete) && $key !== $concrete) { $this->aliases[$key] = $concrete; $key = $concrete; } // we need to build a definition $definition = Definition::factory($key, $concrete, $this); $this->items[$key] = [ 'definition' => $definition, 'singleton' => $singleton, ]; return $definition; } /** * Alias a string to map to a registered item in the container. This allows * you to call 'make' on an alias that maps to a more complex class name, * Closure, or singleton instance. * * @param $alias string The alias to register * @param $key string The original class name or key registered * * @return $this Return the depository for fluent method chaining */ public function alias($alias, $key): this { if (isset($this->aliases[$alias])) { throw new AlreadyRegisteredException("Alias $alias has already been mapped to {$this->aliases[$alias]}"); } $this->aliases[$alias] = $key; return $this; } /** * Register a new singleton in the container * * @param string $alias The alias (container key) for the registered item * @param mixed $concrete The class name, closure, object to register in * the container, or null to use the alias as the * class name * * @return object|$definition Either the concrete (if an object is registered) * or the definition of the registered item */ public function singleton(string $alias, ?mixed $concrete): mixed { return $this->register($alias, $concrete, true); } /** * Retrieve (and build if necessary) the registered item from the container * * @param string $alias The alias that the item was registered as * @param mixed ...$arguments Additional arguments to pass into the object * during * * @return mixed */ public function make($alias, ...$arguments) { if ($alias instanceof Closure || is_callable($alias)) { $definition = $this->buildCallable($alias); return $definition->create(...$arguments); } if (isset($this->aliases[$alias])) { return $this->make($this->aliases[$alias], ...$arguments); } if (isset($this->singletons[$alias])) { return $this->singletons[$alias]; } if (array_key_exists($alias, $this->items)) { $definition = $this->items[$alias]['definition']; $retval = $definition; if ($definition instanceof Definition) { $retval = $definition->create(...$arguments); } if (isset($this->items[$alias]['singleton']) && $this->items[$alias]['singleton'] === true) { unset($this->items[$alias]); $this->singletons[$alias] = $retval; } return $retval; } if (class_exists($alias)) { $definition = $this->buildClass($alias); $this->items[$alias]['definition'] = $definition; } else { $definition = $this->buildCallable($alias); $this->items[$alias]['definition'] = $definition; } return $definition->create(...$arguments); } /** * This method will use reflection to build the class and inject any * necessary arguments for construction. * * @param string $class The class name to reflect and construct * @param mixed ...$parameters Parameters required for constructing the object * * @return ClosureDefinition|CallableDefinition|ClassDefinition|Definition\mixed * @throws ReflectionException */ protected function buildClass(string $class): Definition { if (!class_exists($class)) { throw new ReflectionException("Class $class does not exist."); } $reflection = new ReflectionClass($class); if (!$reflection->isInstantiable()) { $message = "Target [$class] is not instantiable."; throw new ReflectionException($message); } $definition = Definition::factory($class, $class, $this); $constructor = $reflection->getConstructor(); if (is_null($constructor)) { return $definition; } foreach ($constructor->getParameters() as $param) { $dependency = $param->getClass(); if (is_null($dependency)) { if ($param->isDefaultValueAvailable()) { $definition->with($param->getDefaultValue()); continue; } throw new ReflectionException("Cannot to resolve dependency of $param for $class"); } $definition->with($dependency->getName()); } return $definition; } /** * This method will use reflection to build a definition of the callable to * be registered by the depository. * * @param string $alias */ protected function buildCallable($alias): Definition { if (is_string($alias) && strpos($alias, '::') !== false) { $callable = explode('::', $alias); } else { $callable = $alias; if (!is_string($alias)) { $alias = 'Callable'; } } $definition = Definition::factory($alias, $callable, $this); if (is_array($callable)) { $reflector = new ReflectionMethod($callable[0], $callable[1]); } else { $reflector = new ReflectionFunction($callable); } foreach ($reflector->getParameters() as $param) { $dependency = $param->getClass(); if (is_null($dependency)) { if ($param->isDefaultValueAvailable()) { $definition->with($param->getDefaultValue()); continue; } throw new ReflectionException("Cannot to resolve dependency of $param for $alias"); } $definition->with($dependency->getName()); } return $definition; } /** * Return whether or not an alias has been registered in the container * * @param string $alias Registered key or class name * * @return bool */ public function has(string $alias): bool { if (isset($this->singletons[$alias])) { return true; } if (isset($this->items[$alias])) { return true; } return false; } /** * Return whether or not an alias has been registered as a singleton in * the container * * @param string $alias Registered key or class name * * @return bool */ public function isSingleton(string $alias) { if (isset($this->singletons[$alias]) || (isset($this->items[$alias]) && $this->items[$alias]['singleton'] === true)) { return true; } return false; } /** * {@inheritdoc} */ public function offsetExists(mixed $key): bool { return $this->has($key); } /** * {@inheritdoc} */ public function offsetGet(mixed $key): mixed { return $this->make($key); } /** * {@inheritdoc} */ public function offsetSet(mixed $key, $value): mixed { return $this->register($key, $value); } /** * {@inheritdoc} */ public function offsetUnset(mixed $key) { unset($this->singletons[$key]); unset($this->items[$key]); if (isset($this->aliases[$key])) { unset($this->singletons[$this->aliases[$key]]); unset($this->items[$this->aliases[$key]]); unset($this->aliases[$key]); } } }<commit_msg>reverted isRegistered function name<commit_after><?hh // strict /** * @copyright 2010-2015, The Titon Project * @license http://opensource.org/licenses/bsd-license.php * @link http://titon.io */ namespace Titon\Context; use Closure; use ArrayAccess; use ReflectionClass; use ReflectionMethod; use ReflectionFunction; use ReflectionException; use Titon\Context\Definition\CallableDefinition; use Titon\Context\Definition\ClosureDefinition; use Titon\Context\Definition\ClassDefinition; use Titon\Context\Definition\Definition; use Titon\Context\Exception\AlreadyRegisteredException; /** * The depository serves as a dependency injector. After registering an object, * class, or callable with the depository, retrieving it will handle any necessary * dependency injection and reflection resolution before returning the object for * use. * * @package Titon\Context */ class Depository implements ArrayAccess { /** * Hash of registered item definitions keyed by its alias or class name * * @var array */ protected array $items = []; /** * Hash of registered, and already constructed, singletons keyed by its * alias or class name * * @var array */ protected array $singletons = []; /** * Map of aliases to registered classes and keys * * @var AliasMap */ protected AliasMap $aliases = Map{}; /** * Instantiate a new container object */ public function __construct() { $this->register('Titon\Context\Depository', $this); } /** * Register a new class, callable, or object in the container * * @param string $key The alias (container key) for the registered item * @param mixed $concrete The class name, closure, object to register in * the container, or null to use the alias as the * class name * @param bool $singleton Whether or not the container should register the * concrete as a singleton or not (only if concrete * is class name or a closure) * * @return object|$definition Either the concrete (if an object is registered) * or the definition of the registered item */ public function register(string $key, ?mixed $concrete = null, boolean $singleton = false): mixed { if (isset($this[$key]) || isset($this->aliases[$key])) { throw new AlreadyRegisteredException("Key $key has already been registered"); } if (is_null($concrete)) { $concrete = $key; } if (is_object($concrete) && !($concrete instanceof Closure)) { if ($key !== get_class($concrete)) { $this->aliases[$key] = get_class($concrete); $key = get_class($concrete); } $this->singletons[$key] = $concrete; return $concrete; } if (is_string($concrete) && $key !== $concrete) { $this->aliases[$key] = $concrete; $key = $concrete; } // we need to build a definition $definition = Definition::factory($key, $concrete, $this); $this->items[$key] = [ 'definition' => $definition, 'singleton' => $singleton, ]; return $definition; } /** * Alias a string to map to a registered item in the container. This allows * you to call 'make' on an alias that maps to a more complex class name, * Closure, or singleton instance. * * @param $alias string The alias to register * @param $key string The original class name or key registered * * @return $this Return the depository for fluent method chaining */ public function alias($alias, $key): this { if (isset($this->aliases[$alias])) { throw new AlreadyRegisteredException("Alias $alias has already been mapped to {$this->aliases[$alias]}"); } $this->aliases[$alias] = $key; return $this; } /** * Register a new singleton in the container * * @param string $alias The alias (container key) for the registered item * @param mixed $concrete The class name, closure, object to register in * the container, or null to use the alias as the * class name * * @return object|$definition Either the concrete (if an object is registered) * or the definition of the registered item */ public function singleton(string $alias, ?mixed $concrete): mixed { return $this->register($alias, $concrete, true); } /** * Retrieve (and build if necessary) the registered item from the container * * @param string $alias The alias that the item was registered as * @param mixed ...$arguments Additional arguments to pass into the object * during * * @return mixed */ public function make($alias, ...$arguments) { if ($alias instanceof Closure || is_callable($alias)) { $definition = $this->buildCallable($alias); return $definition->create(...$arguments); } if (isset($this->aliases[$alias])) { return $this->make($this->aliases[$alias], ...$arguments); } if (isset($this->singletons[$alias])) { return $this->singletons[$alias]; } if (array_key_exists($alias, $this->items)) { $definition = $this->items[$alias]['definition']; $retval = $definition; if ($definition instanceof Definition) { $retval = $definition->create(...$arguments); } if (isset($this->items[$alias]['singleton']) && $this->items[$alias]['singleton'] === true) { unset($this->items[$alias]); $this->singletons[$alias] = $retval; } return $retval; } if (class_exists($alias)) { $definition = $this->buildClass($alias); $this->items[$alias]['definition'] = $definition; } else { $definition = $this->buildCallable($alias); $this->items[$alias]['definition'] = $definition; } return $definition->create(...$arguments); } /** * This method will use reflection to build the class and inject any * necessary arguments for construction. * * @param string $class The class name to reflect and construct * @param mixed ...$parameters Parameters required for constructing the object * * @return ClosureDefinition|CallableDefinition|ClassDefinition|Definition\mixed * @throws ReflectionException */ protected function buildClass(string $class): Definition { if (!class_exists($class)) { throw new ReflectionException("Class $class does not exist."); } $reflection = new ReflectionClass($class); if (!$reflection->isInstantiable()) { $message = "Target [$class] is not instantiable."; throw new ReflectionException($message); } $definition = Definition::factory($class, $class, $this); $constructor = $reflection->getConstructor(); if (is_null($constructor)) { return $definition; } foreach ($constructor->getParameters() as $param) { $dependency = $param->getClass(); if (is_null($dependency)) { if ($param->isDefaultValueAvailable()) { $definition->with($param->getDefaultValue()); continue; } throw new ReflectionException("Cannot to resolve dependency of $param for $class"); } $definition->with($dependency->getName()); } return $definition; } /** * This method will use reflection to build a definition of the callable to * be registered by the depository. * * @param string $alias */ protected function buildCallable($alias): Definition { if (is_string($alias) && strpos($alias, '::') !== false) { $callable = explode('::', $alias); } else { $callable = $alias; if (!is_string($alias)) { $alias = 'Callable'; } } $definition = Definition::factory($alias, $callable, $this); if (is_array($callable)) { $reflector = new ReflectionMethod($callable[0], $callable[1]); } else { $reflector = new ReflectionFunction($callable); } foreach ($reflector->getParameters() as $param) { $dependency = $param->getClass(); if (is_null($dependency)) { if ($param->isDefaultValueAvailable()) { $definition->with($param->getDefaultValue()); continue; } throw new ReflectionException("Cannot to resolve dependency of $param for $alias"); } $definition->with($dependency->getName()); } return $definition; } /** * Return whether or not an alias has been registered in the container * * @param string $alias Registered key or class name * * @return bool */ public function isRegistered(string $alias): bool { if (isset($this->singletons[$alias])) { return true; } if (isset($this->items[$alias])) { return true; } return false; } /** * Return whether or not an alias has been registered as a singleton in * the container * * @param string $alias Registered key or class name * * @return bool */ public function isSingleton(string $alias) { if (isset($this->singletons[$alias]) || (isset($this->items[$alias]) && $this->items[$alias]['singleton'] === true)) { return true; } return false; } /** * {@inheritdoc} */ public function offsetExists(mixed $key): bool { return $this->isRegistered($key); } /** * {@inheritdoc} */ public function offsetGet(mixed $key): mixed { return $this->make($key); } /** * {@inheritdoc} */ public function offsetSet(mixed $key, $value): mixed { return $this->register($key, $value); } /** * {@inheritdoc} */ public function offsetUnset(mixed $key) { unset($this->singletons[$key]); unset($this->items[$key]); if (isset($this->aliases[$key])) { unset($this->singletons[$this->aliases[$key]]); unset($this->items[$this->aliases[$key]]); unset($this->aliases[$key]); } } }<|endoftext|>
<commit_before>#include "BedFile.h" #include "ToolBase.h" #include "NGSHelper.h" #include "BasicStatistics.h" #include "FastaFileIndex.h" #include "Settings.h" #include "Exceptions.h" #include <cmath> class ConcreteTool : public ToolBase { Q_OBJECT public: ConcreteTool(int& argc, char *argv[]) : ToolBase(argc, argv) { } virtual void setup() { setDescription("Annotates a variant list with variant frequencies from a BAM/CRAM file."); addInfile("in", "Input variant list to annotate in GSvar format.", false, true); addInfile("bam", "Input BAM/CRAM file.", false, true); addOutfile("out", "Output variant list file name (VCF or GSvar).", false, true); //optional addInfile("ref", "Reference genome FASTA file. If unset 'reference_genome' from the 'settings.ini' file is used.", true, false); addString("ref_cram", "Reference genome for CRAM support (mandatory if CRAM is used).", true); changeLog(2021, 06, 24, "Initial version."); } //binomial distribution density double binom(int x, int n, double p) { return std::pow(p, x) * std::pow(1-p, n-x) * BasicStatistics::factorial(n) / BasicStatistics::factorial(x) / BasicStatistics::factorial(n-x); } //binomial test p-value double binomtest_p(int x, int n, double p) { //for high coverage (~160x), downsample alternative observation and depth while (!BasicStatistics::isValidFloat(BasicStatistics::factorial(n))) { x /= 2; n /= 2; } double pval = 0; //sum of all probabilities <= prob_x double prob_x = binom(x, n, p); for (int i=0; i<=n; ++i) { double prob_i = binom(i, n, p); if (prob_i <= prob_x) { pval += prob_i; } } return pval; } //binomial test p-value for p=0.5 double binomtest_p05(int x, int n) { //calculate binomial test p-value, one-sided, with p=0.5 double pval = 0.0; //if observed p <= 0.5, use range 0..x //if observed p > 0.5, use range 0..(n-x) double obs_p = 1.0 * x / n; int limit = obs_p <= 0.5 ? x : n -x; for (int x=0; x <= limit; ++x) { pval += binom(x, n, 0.5); } //for p=0.5, p-value for two-sided test is 2 * p-value for one sided test if (BasicStatistics::isValidFloat(pval)) { pval = std::min(1.0, 2. * pval); } return pval; } virtual void main() { //init QString ref_file = getInfile("ref"); if (ref_file=="") ref_file = Settings::string("reference_genome", true); if (ref_file=="") THROW(CommandLineParsingException, "Reference genome FASTA unset in both command-line and settings.ini file!"); //factorials cache BasicStatistics::precalculateFactorials(); //load DNA variants VariantList input; input.load(getInfile("in")); //reader for RNA BAM file BamReader reader(getInfile("bam"), getString("ref_cram")); //somatic: find tumor_af column, germline: find by sample name bool somatic = input.type(false) == SOMATIC_PAIR || input.type(false) == SOMATIC_SINGLESAMPLE; QString col_name = somatic ? "tumor_af" : input.mainSampleName(); int col_idx = input.annotationIndexByName(col_name); //iterate over input variants and calculate ASE probability FastaFileIndex reference(ref_file); for (int i=0; i<input.count(); ++i) { Variant& variant = input[i]; VariantDetails tmp = reader.getVariantDetails(reference, variant); //no coverage if (tmp.depth==0 || !BasicStatistics::isValidFloat(tmp.frequency)) { variant.annotations().append("n/a (no coverage)"); variant.annotations().append(QByteArray::number(tmp.depth)); variant.annotations().append("n/a (no coverage)"); variant.annotations().append("n/a (no coverage)"); continue; } //number of alternative observations (successes in binomial test) int alt_obs = tmp.depth * tmp.frequency; //output string for p-value QByteArray pval_str; //germline, skip non-het variants if (!somatic && variant.annotations()[col_idx] != "het") { pval_str = "n/a (non-het)"; } else { //use p=0.5 (germline het), or p=tumor_af (somatic) double prob = somatic ? Helper::toDouble(variant.annotations()[col_idx]) : 0.5; double pval = binomtest_p(alt_obs, tmp.depth, prob); pval_str = QByteArray::number(pval, 'f', 4); } //append values variant.annotations().append(QByteArray::number(tmp.frequency, 'f', 4)); variant.annotations().append(QByteArray::number(tmp.depth)); variant.annotations().append(QByteArray::number(alt_obs)); variant.annotations().append(pval_str); } //add annotation headers input.annotations().append(VariantAnnotationHeader("ASE_af")); input.annotationDescriptions().append(VariantAnnotationDescription("ASE_freq", "Expressed variant allele frequency.", VariantAnnotationDescription::FLOAT)); input.annotations().append(VariantAnnotationHeader("ASE_depth")); input.annotationDescriptions().append(VariantAnnotationDescription("ASE_depth", "Sequencing depth at the variant position.", VariantAnnotationDescription::INTEGER)); input.annotations().append(VariantAnnotationHeader("ASE_alt")); input.annotationDescriptions().append(VariantAnnotationDescription("ASE_alt", "Expressed variant alternative observation count.", VariantAnnotationDescription::INTEGER)); input.annotations().append(VariantAnnotationHeader("ASE_pval")); input.annotationDescriptions().append(VariantAnnotationDescription("ASE_pval", "Binomial test p-value.", VariantAnnotationDescription::FLOAT)); input.addCommentLine("##VariantAnnotateASE_BAM=" + getInfile("bam")); //write output input.store(getOutfile("out")); } }; #include "main.moc" int main(int argc, char *argv[]) { ConcreteTool tool(argc, argv); return tool.execute(); } <commit_msg>VariantAnnotateASE: use alternative observation count<commit_after>#include "BedFile.h" #include "ToolBase.h" #include "NGSHelper.h" #include "BasicStatistics.h" #include "FastaFileIndex.h" #include "Settings.h" #include "Exceptions.h" #include <cmath> class ConcreteTool : public ToolBase { Q_OBJECT public: ConcreteTool(int& argc, char *argv[]) : ToolBase(argc, argv) { } virtual void setup() { setDescription("Annotates a variant list with variant frequencies from a BAM/CRAM file."); addInfile("in", "Input variant list to annotate in GSvar format.", false, true); addInfile("bam", "Input BAM/CRAM file.", false, true); addOutfile("out", "Output variant list file name (VCF or GSvar).", false, true); //optional addInfile("ref", "Reference genome FASTA file. If unset 'reference_genome' from the 'settings.ini' file is used.", true, false); addString("ref_cram", "Reference genome for CRAM support (mandatory if CRAM is used).", true); changeLog(2021, 06, 24, "Initial version."); } //binomial distribution density double binom(int x, int n, double p) { return std::pow(p, x) * std::pow(1-p, n-x) * BasicStatistics::factorial(n) / BasicStatistics::factorial(x) / BasicStatistics::factorial(n-x); } //binomial test p-value double binomtest_p(int x, int n, double p) { //for high coverage (~160x), downsample alternative observation and depth while (!BasicStatistics::isValidFloat(BasicStatistics::factorial(n))) { x /= 2; n /= 2; } double pval = 0; //sum of all probabilities <= prob_x double prob_x = binom(x, n, p); for (int i=0; i<=n; ++i) { double prob_i = binom(i, n, p); if (prob_i <= prob_x) { pval += prob_i; } } return pval; } //binomial test p-value for p=0.5 double binomtest_p05(int x, int n) { //calculate binomial test p-value, one-sided, with p=0.5 double pval = 0.0; //if observed p <= 0.5, use range 0..x //if observed p > 0.5, use range 0..(n-x) double obs_p = 1.0 * x / n; int limit = obs_p <= 0.5 ? x : n -x; for (int x=0; x <= limit; ++x) { pval += binom(x, n, 0.5); } //for p=0.5, p-value for two-sided test is 2 * p-value for one sided test if (BasicStatistics::isValidFloat(pval)) { pval = std::min(1.0, 2. * pval); } return pval; } virtual void main() { //init QString ref_file = getInfile("ref"); if (ref_file=="") ref_file = Settings::string("reference_genome", true); if (ref_file=="") THROW(CommandLineParsingException, "Reference genome FASTA unset in both command-line and settings.ini file!"); //factorials cache BasicStatistics::precalculateFactorials(); //load DNA variants VariantList input; input.load(getInfile("in")); //reader for RNA BAM file BamReader reader(getInfile("bam"), getString("ref_cram")); //somatic: find tumor_af column, germline: find by sample name bool somatic = input.type(false) == SOMATIC_PAIR || input.type(false) == SOMATIC_SINGLESAMPLE; QString col_name = somatic ? "tumor_af" : input.mainSampleName(); int col_idx = input.annotationIndexByName(col_name); //iterate over input variants and calculate ASE probability FastaFileIndex reference(ref_file); for (int i=0; i<input.count(); ++i) { Variant& variant = input[i]; VariantDetails tmp = reader.getVariantDetails(reference, variant); //no coverage if (tmp.depth==0 || !BasicStatistics::isValidFloat(tmp.frequency)) { variant.annotations().append("n/a (no coverage)"); variant.annotations().append(QByteArray::number(tmp.depth)); variant.annotations().append("n/a (no coverage)"); variant.annotations().append("n/a (no coverage)"); continue; } //output string for p-value QByteArray pval_str; //germline, skip non-het variants if (!somatic && variant.annotations()[col_idx] != "het") { pval_str = "n/a (non-het)"; } else { //use p=0.5 (germline het), or p=tumor_af (somatic) double prob = somatic ? Helper::toDouble(variant.annotations()[col_idx]) : 0.5; double pval = binomtest_p(tmp.obs, tmp.depth, prob); pval_str = QByteArray::number(pval, 'f', 4); } //append values variant.annotations().append(QByteArray::number(tmp.frequency, 'f', 4)); variant.annotations().append(QByteArray::number(tmp.depth)); variant.annotations().append(QByteArray::number(tmp.obs)); variant.annotations().append(pval_str); } //add annotation headers input.annotations().append(VariantAnnotationHeader("ASE_af")); input.annotationDescriptions().append(VariantAnnotationDescription("ASE_freq", "Expressed variant allele frequency.", VariantAnnotationDescription::FLOAT)); input.annotations().append(VariantAnnotationHeader("ASE_depth")); input.annotationDescriptions().append(VariantAnnotationDescription("ASE_depth", "Sequencing depth at the variant position.", VariantAnnotationDescription::INTEGER)); input.annotations().append(VariantAnnotationHeader("ASE_alt")); input.annotationDescriptions().append(VariantAnnotationDescription("ASE_alt", "Expressed variant alternative observation count.", VariantAnnotationDescription::INTEGER)); input.annotations().append(VariantAnnotationHeader("ASE_pval")); input.annotationDescriptions().append(VariantAnnotationDescription("ASE_pval", "Binomial test p-value.", VariantAnnotationDescription::FLOAT)); input.addCommentLine("##VariantAnnotateASE_BAM=" + getInfile("bam")); //write output input.store(getOutfile("out")); } }; #include "main.moc" int main(int argc, char *argv[]) { ConcreteTool tool(argc, argv); return tool.execute(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2013 The Communi Project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "sorterplugin.h" #include "treewidget.h" #include "treeitem.h" #include <QMouseEvent> #include <QStringList> #include <QSettings> #include <QDebug> #include <QHash> typedef QHash<QString, QStringList> QHashStringList; Q_GLOBAL_STATIC(QStringList, topLevelSortOrder) Q_GLOBAL_STATIC(QHashStringList, childSortOrders) bool CustomTreeSorter(const TreeItem* one, const TreeItem* another) { QStringList order; const TreeItem* parent = one->parentItem(); if (!parent) order = *topLevelSortOrder(); else order = childSortOrders()->value(parent->text(0)); const int oidx = order.indexOf(one->text(0)); const int aidx = order.indexOf(another->text(0)); if (oidx != -1 && aidx == -1) return true; if (aidx != -1 && oidx == -1) return false; return oidx < aidx; } SorterPlugin::SorterPlugin(QObject* parent) : QObject(parent) { d.tree = 0; d.action = 0; } void SorterPlugin::initialize(TreeWidget* tree) { d.tree = tree; d.action = new QAction(tr("Sort"), tree); connect(d.action, SIGNAL(toggled(bool)), this, SLOT(toggleSorting(bool))); d.action->setCheckable(true); d.tree->addAction(d.action); QSettings settings; settings.beginGroup("Sorting"); toggleSorting(settings.value("enabled", true).toBool()); d.tree->viewport()->installEventFilter(this); connect(tree, SIGNAL(itemPressed(QTreeWidgetItem*,int)), this, SLOT(onPressed(QTreeWidgetItem*))); } void SorterPlugin::uninitialize(TreeWidget* tree) { QSettings settings; settings.beginGroup("Sorting"); settings.setValue("enabled", d.tree->isSortingEnabled()); tree->viewport()->removeEventFilter(this); } bool SorterPlugin::eventFilter(QObject* object, QEvent* event) { Q_UNUSED(object); if (d.source) { if (event->type() == QEvent::MouseMove) { QMouseEvent* me = static_cast<QMouseEvent*>(event); QTreeWidgetItem* target = d.tree->itemAt(me->pos()); if (target && target->parent() && d.source != target && d.source->parent() == target->parent()) { setSortingEnabled(false); QTreeWidgetItem* parent = target->parent(); int idx = parent->indexOfChild(target); parent->takeChild(parent->indexOfChild(d.source)); parent->insertChild(idx, d.source); saveOrder(); } } else if (event->type() == QEvent::MouseButtonRelease) { d.source = 0; } } return false; } void SorterPlugin::toggleSorting(bool enabled) { if (!enabled) restoreOrder(); setSortingEnabled(enabled); } void SorterPlugin::setSortingEnabled(bool enabled) { if (d.tree->isSortingEnabled() != enabled) { d.tree->setSorter(enabled ? DefaultTreeSorter : CustomTreeSorter); d.tree->setSortingEnabled(enabled); d.tree->sortByColumn(0, Qt::AscendingOrder); } d.action->blockSignals(true); d.action->setChecked(enabled); d.action->blockSignals(false); } void SorterPlugin::onPressed(QTreeWidgetItem* item) { d.source = item; } void SorterPlugin::saveOrder() { QSettings settings; settings.beginGroup("Sorting"); QHash<QString, QVariant> children; for (int i = 0; i < d.tree->topLevelItemCount(); ++i) { QStringList texts; QTreeWidgetItem* parent = d.tree->topLevelItem(i); for (int j = 0; j < parent->childCount(); ++j) texts += parent->child(j)->text(0); children.insert(parent->text(0), texts); } settings.setValue("children", children); settings.setValue("parents", *topLevelSortOrder()); } void SorterPlugin::restoreOrder() { QSettings settings; settings.beginGroup("Sorting"); QHashIterator<QString, QVariant> it(settings.value("children").toHash()); while (it.hasNext()) { it.next(); *childSortOrders()->insert(it.key(), it.value().toStringList()); } *topLevelSortOrder() = settings.value("parents").toStringList(); } #if QT_VERSION < 0x050000 Q_EXPORT_STATIC_PLUGIN(SorterPlugin) #endif <commit_msg>WIP: sorting<commit_after>/* * Copyright (C) 2008-2013 The Communi Project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "sorterplugin.h" #include "treewidget.h" #include "treeitem.h" #include <QMouseEvent> #include <QStringList> #include <QSettings> #include <QDebug> #include <QHash> typedef QHash<QString, QStringList> QHashStringList; Q_GLOBAL_STATIC(QStringList, topLevelSortOrder) Q_GLOBAL_STATIC(QHashStringList, childSortOrders) bool CustomTreeSorter(const TreeItem* one, const TreeItem* another) { QStringList order; const TreeItem* parent = one->parentItem(); if (!parent) order = *topLevelSortOrder(); else order = childSortOrders()->value(parent->text(0)); const int oidx = order.indexOf(one->text(0)); const int aidx = order.indexOf(another->text(0)); if (oidx == -1 && aidx == -1) return DefaultTreeSorter(one, another); if (oidx != -1 && aidx == -1) return true; if (aidx != -1 && oidx == -1) return false; return oidx < aidx; } SorterPlugin::SorterPlugin(QObject* parent) : QObject(parent) { d.tree = 0; d.action = 0; } void SorterPlugin::initialize(TreeWidget* tree) { d.tree = tree; d.action = new QAction(tr("Sort"), tree); connect(d.action, SIGNAL(toggled(bool)), this, SLOT(toggleSorting(bool))); d.action->setCheckable(true); d.tree->addAction(d.action); QSettings settings; settings.beginGroup("Sorting"); toggleSorting(settings.value("enabled", true).toBool()); d.tree->viewport()->installEventFilter(this); connect(tree, SIGNAL(itemPressed(QTreeWidgetItem*,int)), this, SLOT(onPressed(QTreeWidgetItem*))); } void SorterPlugin::uninitialize(TreeWidget* tree) { QSettings settings; settings.beginGroup("Sorting"); settings.setValue("enabled", d.tree->isSortingEnabled()); tree->viewport()->removeEventFilter(this); } bool SorterPlugin::eventFilter(QObject* object, QEvent* event) { Q_UNUSED(object); if (d.source) { if (event->type() == QEvent::MouseMove) { QMouseEvent* me = static_cast<QMouseEvent*>(event); QTreeWidgetItem* target = d.tree->itemAt(me->pos()); if (target && target->parent() && d.source != target && d.source->parent() == target->parent()) { setSortingEnabled(false); QTreeWidgetItem* parent = target->parent(); int idx = parent->indexOfChild(target); parent->takeChild(parent->indexOfChild(d.source)); parent->insertChild(idx, d.source); saveOrder(); } } else if (event->type() == QEvent::MouseButtonRelease) { d.source = 0; } } return false; } void SorterPlugin::toggleSorting(bool enabled) { if (!enabled) restoreOrder(); setSortingEnabled(enabled); if (!enabled) d.tree->sortByColumn(0, Qt::AscendingOrder); } void SorterPlugin::setSortingEnabled(bool enabled) { const bool wasEnabled = d.tree->isSortingEnabled(); d.tree->setSorter(enabled ? DefaultTreeSorter : CustomTreeSorter); d.tree->setSortingEnabled(enabled); if (enabled && !wasEnabled) d.tree->sortByColumn(0, Qt::AscendingOrder); d.action->blockSignals(true); d.action->setChecked(enabled); d.action->blockSignals(false); } void SorterPlugin::onPressed(QTreeWidgetItem* item) { d.source = item; } void SorterPlugin::saveOrder() { QSettings settings; settings.beginGroup("Sorting"); QStringList parents; QHash<QString, QVariant> children; for (int i = 0; i < d.tree->topLevelItemCount(); ++i) { QStringList lst; QTreeWidgetItem* parent = d.tree->topLevelItem(i); for (int j = 0; j < parent->childCount(); ++j) lst += parent->child(j)->text(0); children.insert(parent->text(0), lst); parents += parent->text(0); } settings.setValue("children", children); settings.setValue("parents", parents); } void SorterPlugin::restoreOrder() { QSettings settings; settings.beginGroup("Sorting"); QHashIterator<QString, QVariant> it(settings.value("children").toHash()); while (it.hasNext()) { it.next(); *childSortOrders()->insert(it.key(), it.value().toStringList()); } *topLevelSortOrder() = settings.value("parents").toStringList(); } #if QT_VERSION < 0x050000 Q_EXPORT_STATIC_PLUGIN(SorterPlugin) #endif <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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. */ /** \file TransferFunction2D.cpp \author Jens Krueger SCI Institute University of Utah \version 1.0 \date July 2008 */ #include "TransferFunction2D.h" using namespace std; TransferFunction2D::TransferFunction2D() { Resize(VECTOR2<size_t>(0,0)); } TransferFunction2D::TransferFunction2D(const VECTOR2<size_t>& iSize) { Resize(iSize); } TransferFunction2D::~TransferFunction2D(void) { } void TransferFunction2D::Resize(const VECTOR2<size_t>& iSize) { pColorData.Resize(iSize); } bool TransferFunction2D::Load(const std::string& filename) { ifstream file(filename.c_str()); if (!file.is_open()) return false; // load gridsize UINTVECTOR2 iSize; file >> iSize.x; file >> iSize.y; pColorData.Resize(iSize); // load swatch count unsigned int iSwatchCount; file >> iSwatchCount; m_Swatches.resize(iSwatchCount); // load Swatches for (unsigned int i = 0;i<m_Swatches.size();i++) m_Swatches[i].Load(file); return true; } bool TransferFunction2D::Save(const std::string& filename) { ofstream file(filename.c_str()); if (!file.is_open()) return false; // save gridsize file << pColorData.GetSize().x << " " << pColorData.GetSize().y << " "; // save swatch count file << m_Swatches.size() << " "; // save Swatches for (unsigned int i = 0;i<m_Swatches.size();i++) m_Swatches[i].Save(file); return true; } void TransferFunction2D::GetByteArray(unsigned char** pcData, unsigned char cUsedRange) { if (*pcData == NULL) *pcData = new unsigned char[pColorData.GetSize().area()]; unsigned char *pcDataIterator = *pcData; FLOATVECTOR4 *piSourceIterator = pColorData.GetDataPointer(); for (unsigned int i = 0;i<pColorData.GetSize().area();i++) { *pcDataIterator++ = (unsigned char)((*piSourceIterator)[0]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[1]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[2]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[3]*cUsedRange); piSourceIterator++; } } void TransferFunction2D::GetShortArray(unsigned short** psData, unsigned short sUsedRange) { if (*psData == NULL) *psData = new unsigned short[pColorData.GetSize().area()]; unsigned short *psDataIterator = *psData; FLOATVECTOR4 *piSourceIterator = pColorData.GetDataPointer(); for (unsigned int i = 0;i<pColorData.GetSize().area();i++) { *psDataIterator++ = (unsigned short)((*piSourceIterator)[0]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[1]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[2]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[3]*sUsedRange); piSourceIterator++; } } void TransferFunction2D::GetFloatArray(float** pfData) { if (*pfData == NULL) *pfData = new float[4*pColorData.GetSize().area()]; memcpy(*pfData, pColorData.GetDataPointer(), 4*sizeof(float)*pColorData.GetSize().area()); } void TFPolygon::Load(ifstream& file) { unsigned int iSize; file >> iSize; pPoints.resize(iSize); for(unsigned int i=0;i<pPoints.size();++i){ for(unsigned int j=0;j<2;++j){ file >> pPoints[i][j]; } } file >> pGradientCoords[0][0] >> pGradientCoords[0][1]; file >> pGradientCoords[1][0] >> pGradientCoords[1][1]; file >> iSize; pGradientStops.resize(iSize); for(unsigned int i=0;i<pGradientStops.size();++i){ file >> pGradientStops[i].first; for(unsigned int j=0;j<4;++j){ file >> pGradientStops[i].second[j]; } } } void TFPolygon::Save(ofstream& file) { file << pPoints.size() << " "; for(unsigned int i=0;i<pPoints.size();++i){ for(unsigned int j=0;j<2;++j){ file << pPoints[i][j] << " "; } file << endl; } file << pGradientCoords[0][0] << " " << pGradientCoords[0][1] << " "; file << pGradientCoords[1][0] << " " << pGradientCoords[1][1]; file << endl; file << pGradientStops.size() << " "; for(unsigned int i=0;i<pGradientStops.size();++i){ file << pGradientStops[i].first << " "; for(unsigned int j=0;j<4;++j){ file << pGradientStops[i].second[j] << " "; } file << endl; } } <commit_msg><commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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. */ /** \file TransferFunction2D.cpp \author Jens Krueger SCI Institute University of Utah \version 1.0 \date July 2008 */ #include "TransferFunction2D.h" using namespace std; TransferFunction2D::TransferFunction2D() { Resize(VECTOR2<size_t>(0,0)); } TransferFunction2D::TransferFunction2D(const VECTOR2<size_t>& iSize) { Resize(iSize); } TransferFunction2D::~TransferFunction2D(void) { } void TransferFunction2D::Resize(const VECTOR2<size_t>& iSize) { pColorData.Resize(iSize); } bool TransferFunction2D::Load(const std::string& filename) { ifstream file(filename.c_str()); if (!file.is_open()) return false; // load gridsize VECTOR2<size_t> iSize; file >> iSize.x; file >> iSize.y; pColorData.Resize(iSize); // load swatch count unsigned int iSwatchCount; file >> iSwatchCount; m_Swatches.resize(iSwatchCount); // load Swatches for (unsigned int i = 0;i<m_Swatches.size();i++) m_Swatches[i].Load(file); return true; } bool TransferFunction2D::Save(const std::string& filename) { ofstream file(filename.c_str()); if (!file.is_open()) return false; // save gridsize file << pColorData.GetSize().x << " " << pColorData.GetSize().y << " "; // save swatch count file << m_Swatches.size() << " "; // save Swatches for (unsigned int i = 0;i<m_Swatches.size();i++) m_Swatches[i].Save(file); return true; } void TransferFunction2D::GetByteArray(unsigned char** pcData, unsigned char cUsedRange) { if (*pcData == NULL) *pcData = new unsigned char[pColorData.GetSize().area()]; unsigned char *pcDataIterator = *pcData; FLOATVECTOR4 *piSourceIterator = pColorData.GetDataPointer(); for (unsigned int i = 0;i<pColorData.GetSize().area();i++) { *pcDataIterator++ = (unsigned char)((*piSourceIterator)[0]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[1]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[2]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[3]*cUsedRange); piSourceIterator++; } } void TransferFunction2D::GetShortArray(unsigned short** psData, unsigned short sUsedRange) { if (*psData == NULL) *psData = new unsigned short[pColorData.GetSize().area()]; unsigned short *psDataIterator = *psData; FLOATVECTOR4 *piSourceIterator = pColorData.GetDataPointer(); for (unsigned int i = 0;i<pColorData.GetSize().area();i++) { *psDataIterator++ = (unsigned short)((*piSourceIterator)[0]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[1]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[2]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[3]*sUsedRange); piSourceIterator++; } } void TransferFunction2D::GetFloatArray(float** pfData) { if (*pfData == NULL) *pfData = new float[4*pColorData.GetSize().area()]; memcpy(*pfData, pColorData.GetDataPointer(), 4*sizeof(float)*pColorData.GetSize().area()); } void TFPolygon::Load(ifstream& file) { unsigned int iSize; file >> iSize; pPoints.resize(iSize); for(unsigned int i=0;i<pPoints.size();++i){ for(unsigned int j=0;j<2;++j){ file >> pPoints[i][j]; } } file >> pGradientCoords[0][0] >> pGradientCoords[0][1]; file >> pGradientCoords[1][0] >> pGradientCoords[1][1]; file >> iSize; pGradientStops.resize(iSize); for(unsigned int i=0;i<pGradientStops.size();++i){ file >> pGradientStops[i].first; for(unsigned int j=0;j<4;++j){ file >> pGradientStops[i].second[j]; } } } void TFPolygon::Save(ofstream& file) { file << pPoints.size() << " "; for(unsigned int i=0;i<pPoints.size();++i){ for(unsigned int j=0;j<2;++j){ file << pPoints[i][j] << " "; } file << endl; } file << pGradientCoords[0][0] << " " << pGradientCoords[0][1] << " "; file << pGradientCoords[1][0] << " " << pGradientCoords[1][1]; file << endl; file << pGradientStops.size() << " "; for(unsigned int i=0;i<pGradientStops.size();++i){ file << pGradientStops[i].first << " "; for(unsigned int j=0;j<4;++j){ file << pGradientStops[i].second[j] << " "; } file << endl; } } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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. */ /** \file TransferFunction2D.cpp \author Jens Krueger SCI Institute University of Utah \version 1.0 \date July 2008 */ #include "TransferFunction2D.h" using namespace std; TransferFunction2D::TransferFunction2D() { Resize(VECTOR2<size_t>(0,0)); } TransferFunction2D::TransferFunction2D(const VECTOR2<size_t>& iSize) { Resize(iSize); } TransferFunction2D::~TransferFunction2D(void) { } void TransferFunction2D::Resize(const VECTOR2<size_t>& iSize) { pColorData.Resize(iSize); m_Trans1D.Resize(iSize.x); m_Trans1D.Clear(); } bool TransferFunction2D::Load(const std::string& filename) { return Load(filename, pColorData.GetSize()); } bool TransferFunction2D::Load(const std::string& filename, const VECTOR2<size_t>& iSize) { ifstream file(filename.c_str()); if (!file.is_open()) return false; pColorData.Resize(iSize); // load 1D Trans m_Trans1D.Load(file, iSize.x); // load swatch count unsigned int iSwatchCount; file >> iSwatchCount; m_Swatches.resize(iSwatchCount); // load Swatches for (unsigned int i = 0;i<m_Swatches.size();i++) m_Swatches[i].Load(file); file.close(); return true; } bool TransferFunction2D::Save(const std::string& filename) { ofstream file(filename.c_str()); if (!file.is_open()) return false; // save 1D Trans m_Trans1D.Save(file); // save swatch count file << m_Swatches.size() << endl; // save Swatches for (unsigned int i = 0;i<m_Swatches.size();i++) m_Swatches[i].Save(file); file.close(); return true; } void TransferFunction2D::GetByteArray(unsigned char** pcData, unsigned char cUsedRange) { if (*pcData == NULL) *pcData = new unsigned char[pColorData.GetSize().area()]; unsigned char *pcDataIterator = *pcData; FLOATVECTOR4 *piSourceIterator = pColorData.GetDataPointer(); for (unsigned int i = 0;i<pColorData.GetSize().area();i++) { *pcDataIterator++ = (unsigned char)((*piSourceIterator)[0]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[1]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[2]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[3]*cUsedRange); piSourceIterator++; } } void TransferFunction2D::GetShortArray(unsigned short** psData, unsigned short sUsedRange) { if (*psData == NULL) *psData = new unsigned short[pColorData.GetSize().area()]; unsigned short *psDataIterator = *psData; FLOATVECTOR4 *piSourceIterator = pColorData.GetDataPointer(); for (unsigned int i = 0;i<pColorData.GetSize().area();i++) { *psDataIterator++ = (unsigned short)((*piSourceIterator)[0]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[1]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[2]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[3]*sUsedRange); piSourceIterator++; } } void TransferFunction2D::GetFloatArray(float** pfData) { if (*pfData == NULL) *pfData = new float[4*pColorData.GetSize().area()]; memcpy(*pfData, pColorData.GetDataPointer(), 4*sizeof(float)*pColorData.GetSize().area()); } void TFPolygon::Load(ifstream& file) { unsigned int iSize; file >> iSize; pPoints.resize(iSize); for(unsigned int i=0;i<pPoints.size();++i){ for(unsigned int j=0;j<2;++j){ file >> pPoints[i][j]; } } file >> pGradientCoords[0][0] >> pGradientCoords[0][1]; file >> pGradientCoords[1][0] >> pGradientCoords[1][1]; file >> iSize; pGradientStops.resize(iSize); for(unsigned int i=0;i<pGradientStops.size();++i){ file >> pGradientStops[i].first; for(unsigned int j=0;j<4;++j){ file >> pGradientStops[i].second[j]; } } } void TFPolygon::Save(ofstream& file) { file << pPoints.size() << endl; for(unsigned int i=0;i<pPoints.size();++i){ for(unsigned int j=0;j<2;++j){ file << pPoints[i][j] << " "; } file << endl; } file << pGradientCoords[0][0] << " " << pGradientCoords[0][1] << " "; file << pGradientCoords[1][0] << " " << pGradientCoords[1][1]; file << endl; file << pGradientStops.size() << endl; for(unsigned int i=0;i<pGradientStops.size();++i){ file << pGradientStops[i].first << " "; for(unsigned int j=0;j<4;++j){ file << pGradientStops[i].second[j] << " "; } file << endl; } } <commit_msg><commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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. */ /** \file TransferFunction2D.cpp \author Jens Krueger SCI Institute University of Utah \version 1.0 \date July 2008 */ #include "TransferFunction2D.h" #include <memory.h> using namespace std; TransferFunction2D::TransferFunction2D() { Resize(VECTOR2<size_t>(0,0)); } TransferFunction2D::TransferFunction2D(const VECTOR2<size_t>& iSize) { Resize(iSize); } TransferFunction2D::~TransferFunction2D(void) { } void TransferFunction2D::Resize(const VECTOR2<size_t>& iSize) { pColorData.Resize(iSize); m_Trans1D.Resize(iSize.x); m_Trans1D.Clear(); } bool TransferFunction2D::Load(const std::string& filename) { return Load(filename, pColorData.GetSize()); } bool TransferFunction2D::Load(const std::string& filename, const VECTOR2<size_t>& iSize) { ifstream file(filename.c_str()); if (!file.is_open()) return false; pColorData.Resize(iSize); // load 1D Trans m_Trans1D.Load(file, iSize.x); // load swatch count unsigned int iSwatchCount; file >> iSwatchCount; m_Swatches.resize(iSwatchCount); // load Swatches for (unsigned int i = 0;i<m_Swatches.size();i++) m_Swatches[i].Load(file); file.close(); return true; } bool TransferFunction2D::Save(const std::string& filename) { ofstream file(filename.c_str()); if (!file.is_open()) return false; // save 1D Trans m_Trans1D.Save(file); // save swatch count file << m_Swatches.size() << endl; // save Swatches for (unsigned int i = 0;i<m_Swatches.size();i++) m_Swatches[i].Save(file); file.close(); return true; } void TransferFunction2D::GetByteArray(unsigned char** pcData, unsigned char cUsedRange) { if (*pcData == NULL) *pcData = new unsigned char[pColorData.GetSize().area()]; unsigned char *pcDataIterator = *pcData; FLOATVECTOR4 *piSourceIterator = pColorData.GetDataPointer(); for (unsigned int i = 0;i<pColorData.GetSize().area();i++) { *pcDataIterator++ = (unsigned char)((*piSourceIterator)[0]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[1]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[2]*cUsedRange); *pcDataIterator++ = (unsigned char)((*piSourceIterator)[3]*cUsedRange); piSourceIterator++; } } void TransferFunction2D::GetShortArray(unsigned short** psData, unsigned short sUsedRange) { if (*psData == NULL) *psData = new unsigned short[pColorData.GetSize().area()]; unsigned short *psDataIterator = *psData; FLOATVECTOR4 *piSourceIterator = pColorData.GetDataPointer(); for (unsigned int i = 0;i<pColorData.GetSize().area();i++) { *psDataIterator++ = (unsigned short)((*piSourceIterator)[0]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[1]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[2]*sUsedRange); *psDataIterator++ = (unsigned short)((*piSourceIterator)[3]*sUsedRange); piSourceIterator++; } } void TransferFunction2D::GetFloatArray(float** pfData) { if (*pfData == NULL) *pfData = new float[4*pColorData.GetSize().area()]; memcpy(*pfData, pColorData.GetDataPointer(), 4*sizeof(float)*pColorData.GetSize().area()); } void TFPolygon::Load(ifstream& file) { unsigned int iSize; file >> iSize; pPoints.resize(iSize); for(unsigned int i=0;i<pPoints.size();++i){ for(unsigned int j=0;j<2;++j){ file >> pPoints[i][j]; } } file >> pGradientCoords[0][0] >> pGradientCoords[0][1]; file >> pGradientCoords[1][0] >> pGradientCoords[1][1]; file >> iSize; pGradientStops.resize(iSize); for(unsigned int i=0;i<pGradientStops.size();++i){ file >> pGradientStops[i].first; for(unsigned int j=0;j<4;++j){ file >> pGradientStops[i].second[j]; } } } void TFPolygon::Save(ofstream& file) { file << pPoints.size() << endl; for(unsigned int i=0;i<pPoints.size();++i){ for(unsigned int j=0;j<2;++j){ file << pPoints[i][j] << " "; } file << endl; } file << pGradientCoords[0][0] << " " << pGradientCoords[0][1] << " "; file << pGradientCoords[1][0] << " " << pGradientCoords[1][1]; file << endl; file << pGradientStops.size() << endl; for(unsigned int i=0;i<pGradientStops.size();++i){ file << pGradientStops[i].first << " "; for(unsigned int j=0;j<4;++j){ file << pGradientStops[i].second[j] << " "; } file << endl; } } <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2009-2011 Emmanuel Benazera <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "sort_rank.h" #include "websearch.h" #include "content_handler.h" #include "urlmatch.h" #include "miscutil.h" #if defined(PROTOBUF) && defined(TC) #include "cf.h" #endif #include <ctype.h> #include <algorithm> #include <iterator> #include <map> #include <iostream> #include <assert.h> using sp::urlmatch; using sp::miscutil; namespace seeks_plugins { void sort_rank::sort_and_merge_snippets(std::vector<search_snippet*> &snippets, std::vector<search_snippet*> &unique_snippets) { // sort snippets by url. std::stable_sort(snippets.begin(),snippets.end(),search_snippet::less_url); // create a set of unique snippets (by url.). std::unique_copy(snippets.begin(),snippets.end(), std::back_inserter(unique_snippets),search_snippet::equal_url); } void sort_rank::sort_merge_and_rank_snippets(query_context *qc, std::vector<search_snippet*> &snippets, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { static double st = 0.9; // similarity threshold. bool content_analysis = websearch::_wconfig->_content_analysis; const char *ca = miscutil::lookup(parameters,"content_analysis"); if (ca && strcasecmp(ca,"on") == 0) content_analysis = true; const char *cache_check = miscutil::lookup(parameters,"ccheck"); bool ccheck = true; if (cache_check && strcasecmp(cache_check,"no") == 0) ccheck = false; // initializes the LSH subsystem is we need it and it has not yet // been initialized. if (content_analysis && !qc->_ulsh_ham) { /** * The LSH system based on a Hamming distance has a fixed maximum size * for strings, it is set to 100. Therefore, k should be set accordingly, * that is below 100 and in proportion to the 'fuzziness' necessary for * k-nearest neighbors computation. */ qc->_lsh_ham = new LSHSystemHamming(55,5); qc->_ulsh_ham = new LSHUniformHashTableHamming(qc->_lsh_ham, websearch::_wconfig->_Nr*3*websearch::_wconfig->_se_enabled.size()); } std::vector<search_snippet*>::iterator it = snippets.begin(); search_snippet *c_sp = NULL; while (it != snippets.end()) { search_snippet *sp = (*it); if (!ccheck && sp->_doc_type == TWEET) sp->_meta_rank = -1; // reset the rank because it includes retweets. if (sp->_new) { if ((c_sp = qc->get_cached_snippet(sp->_id))!=NULL) { // merging snippets. search_snippet::merge_snippets(c_sp,sp); it = snippets.erase(it); delete sp; sp = NULL; continue; } else if (content_analysis) { // grab nearest neighbors out of the LSH uniform hashtable. std::string surl = urlmatch::strip_url(sp->_url); std::map<double,const std::string,std::greater<double> > mres = qc->_ulsh_ham->getLEltsWithProbabilities(surl,qc->_lsh_ham->_Ld); // url. we could treat host & path independently... std::string lctitle = sp->_title; std::transform(lctitle.begin(),lctitle.end(),lctitle.begin(),tolower); std::map<double,const std::string,std::greater<double> > mres_tmp = qc->_ulsh_ham->getLEltsWithProbabilities(lctitle,qc->_lsh_ham->_Ld); // title. std::map<double,const std::string,std::greater<double> >::const_iterator mit = mres_tmp.begin(); while (mit!=mres_tmp.end()) { mres.insert(std::pair<double,const std::string>((*mit).first,(*mit).second)); // we could do better than this merging... ++mit; } if (!mres.empty()) { // iterate results and merge as possible. mit = mres.begin(); while (mit!=mres.end()) { search_snippet *comp_sp = qc->get_cached_snippet((*mit).second); if (!comp_sp) comp_sp = qc->get_cached_snippet_title((*mit).second.c_str()); if (!comp_sp) { // skip this entry. ++mit; continue; } // Beware: second url (from sp) is the one to be possibly deleted! bool same = content_handler::has_same_content(qc,comp_sp,sp,st); if (same) { search_snippet::merge_snippets(comp_sp,sp); it = snippets.erase(it); delete sp; sp = NULL; break; } ++mit; } } // end if mres empty. if (!sp) continue; } //debug //std::cerr << "new url scanned: " << sp->_url << std::endl; //debug sp->_meta_rank = sp->_engine.size(); sp->_new = false; qc->add_to_unordered_cache(sp); qc->add_to_unordered_cache_title(sp); // lsh. if (content_analysis) { std::string surl = urlmatch::strip_url(sp->_url); qc->_ulsh_ham->add(surl,qc->_lsh_ham->_Ld); std::string lctitle = sp->_title; std::transform(lctitle.begin(),lctitle.end(),lctitle.begin(),tolower); qc->_ulsh_ham->add(lctitle,qc->_lsh_ham->_Ld); } } // end if new. ++it; } // end while. // sort by rank. /*std::stable_sort(snippets.begin(),snippets.end(), search_snippet::max_meta_rank);*/ std::stable_sort(snippets.begin(),snippets.end(), search_snippet::max_seeks_rank); //debug /* std::cerr << "[Debug]: sorted result snippets:\n"; it = snippets.begin(); while(it!=snippets.end()) { (*it)->print(std::cerr); it++; i++; } */ //debug } void sort_rank::score_and_sort_by_similarity(query_context *qc, const char *id_str, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, search_snippet *&ref_sp, std::vector<search_snippet*> &sorted_snippets) throw (sp_exception) { uint32_t id = (uint32_t)strtod(id_str,NULL); ref_sp = qc->get_cached_snippet(id); if (!ref_sp) // this should not happen, unless someone is forcing an url onto a Seeks node. throw sp_exception(WB_ERR_NO_REF_SIM,"cannot find ref id among cached snippets"); ref_sp->set_back_similarity_link(parameters); bool content_analysis = websearch::_wconfig->_content_analysis; const char *ca = miscutil::lookup(parameters,"content_analysis"); if (ca && strcasecmp(ca,"on") == 0) content_analysis = true; if (content_analysis) content_handler::fetch_all_snippets_content_and_features(qc); else content_handler::fetch_all_snippets_summary_and_features(qc); // run similarity analysis and compute scores. try { content_handler::feature_based_similarity_scoring(qc,sorted_snippets.size(), &sorted_snippets.at(0),ref_sp); } catch (sp_exception &e) { throw e; } // sort snippets according to computed scores. std::stable_sort(sorted_snippets.begin(),sorted_snippets.end(),search_snippet::max_seeks_ir); } void sort_rank::group_by_types(query_context *qc, cluster *&clusters, short &K) { /** * grouping is done per file type, the most common being: * 0 - html / html aka webpages (but no wikis) * 1 - wiki * 2 - pdf * 3 - .doc, .pps, & so on aka other types of documents. * 4 - forums * 5 - video file * 6 - audio file * 7 - tweets * So for now, K is set to 8. */ K = 8; clusters = new cluster[K]; size_t nsnippets = qc->_cached_snippets.size(); for (size_t i=0; i<nsnippets; i++) { search_snippet *se = qc->_cached_snippets.at(i); if (se->_doc_type == WEBPAGE) { clusters[0].add_point(se->_id,NULL); clusters[0]._label = "Webpages"; // TODO: languages... } else if (se->_doc_type == WIKI) { clusters[1].add_point(se->_id,NULL); clusters[1]._label = "Wikis"; } else if (se->_doc_type == FILE_DOC && se->_file_format == "pdf") { clusters[2].add_point(se->_id,NULL); clusters[2]._label = "PDFs"; } else if (se->_doc_type == FILE_DOC) { clusters[3].add_point(se->_id,NULL); clusters[3]._label = "Other files"; } else if (se->_doc_type == FORUM) { clusters[4].add_point(se->_id,NULL); clusters[4]._label = "Forums"; } else if (se->_doc_type == VIDEO || se->_doc_type == VIDEO_THUMB) { clusters[5].add_point(se->_id,NULL); clusters[5]._label = "Videos"; } else if (se->_doc_type == AUDIO) { clusters[6].add_point(se->_id,NULL); clusters[6]._label = "Audio"; } else if (se->_doc_type == TWEET) { clusters[7].add_point(se->_id,NULL); clusters[7]._label = "Tweets"; } } // sort groups by decreasing sizes. std::stable_sort(clusters,clusters+K,cluster::max_size_cluster); } #if defined(PROTOBUF) && defined(TC) void sort_rank::personalize(query_context *qc) { if (!websearch::_cf_plugin) return; cf *cfp = static_cast<cf*>(websearch::_cf_plugin); cfp->personalize(qc); std::stable_sort(qc->_cached_snippets.begin(),qc->_cached_snippets.end(), search_snippet::max_seeks_rank); } void sort_rank::personalized_rank_snippets(query_context *qc, std::vector<search_snippet*> &snippets) throw (sp_exception) { if (!websearch::_cf_plugin) return; static_cast<cf*>(websearch::_cf_plugin)->estimate_ranks(qc->_query,qc->_auto_lang, qc->_page_expansion,snippets); std::stable_sort(snippets.begin(),snippets.end(), search_snippet::max_seeks_rank); } void sort_rank::get_related_queries(query_context *qc) throw (sp_exception) { if (!websearch::_cf_plugin) return; static_cast<cf*>(websearch::_cf_plugin)->get_related_queries(qc->_query,qc->_auto_lang, qc->_page_expansion,qc->_suggestions); } void sort_rank::get_recommended_urls(query_context *qc) throw (sp_exception) { if (!websearch::_cf_plugin) return; static_cast<cf*>(websearch::_cf_plugin)->get_recommended_urls(qc->_query,qc->_auto_lang, qc->_page_expansion, qc->_recommended_snippets); qc->update_recommended_urls(); } #endif } /* end of namespace. */ <commit_msg>update type sorting function to reflect new snippet types<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2009-2011 Emmanuel Benazera <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "sort_rank.h" #include "websearch.h" #include "content_handler.h" #include "urlmatch.h" #include "miscutil.h" #if defined(PROTOBUF) && defined(TC) #include "cf.h" #endif #include <ctype.h> #include <algorithm> #include <iterator> #include <map> #include <iostream> #include <assert.h> using sp::urlmatch; using sp::miscutil; namespace seeks_plugins { void sort_rank::sort_and_merge_snippets(std::vector<search_snippet*> &snippets, std::vector<search_snippet*> &unique_snippets) { // sort snippets by url. std::stable_sort(snippets.begin(),snippets.end(),search_snippet::less_url); // create a set of unique snippets (by url.). std::unique_copy(snippets.begin(),snippets.end(), std::back_inserter(unique_snippets),search_snippet::equal_url); } void sort_rank::sort_merge_and_rank_snippets(query_context *qc, std::vector<search_snippet*> &snippets, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { static double st = 0.9; // similarity threshold. bool content_analysis = websearch::_wconfig->_content_analysis; const char *ca = miscutil::lookup(parameters,"content_analysis"); if (ca && strcasecmp(ca,"on") == 0) content_analysis = true; const char *cache_check = miscutil::lookup(parameters,"ccheck"); bool ccheck = true; if (cache_check && strcasecmp(cache_check,"no") == 0) ccheck = false; // initializes the LSH subsystem is we need it and it has not yet // been initialized. if (content_analysis && !qc->_ulsh_ham) { /** * The LSH system based on a Hamming distance has a fixed maximum size * for strings, it is set to 100. Therefore, k should be set accordingly, * that is below 100 and in proportion to the 'fuzziness' necessary for * k-nearest neighbors computation. */ qc->_lsh_ham = new LSHSystemHamming(55,5); qc->_ulsh_ham = new LSHUniformHashTableHamming(qc->_lsh_ham, websearch::_wconfig->_Nr*3*websearch::_wconfig->_se_enabled.size()); } std::vector<search_snippet*>::iterator it = snippets.begin(); search_snippet *c_sp = NULL; while (it != snippets.end()) { search_snippet *sp = (*it); if (!ccheck && sp->_doc_type == TWEET) sp->_meta_rank = -1; // reset the rank because it includes retweets. if (sp->_new) { if ((c_sp = qc->get_cached_snippet(sp->_id))!=NULL) { // merging snippets. search_snippet::merge_snippets(c_sp,sp); it = snippets.erase(it); delete sp; sp = NULL; continue; } else if (content_analysis) { // grab nearest neighbors out of the LSH uniform hashtable. std::string surl = urlmatch::strip_url(sp->_url); std::map<double,const std::string,std::greater<double> > mres = qc->_ulsh_ham->getLEltsWithProbabilities(surl,qc->_lsh_ham->_Ld); // url. we could treat host & path independently... std::string lctitle = sp->_title; std::transform(lctitle.begin(),lctitle.end(),lctitle.begin(),tolower); std::map<double,const std::string,std::greater<double> > mres_tmp = qc->_ulsh_ham->getLEltsWithProbabilities(lctitle,qc->_lsh_ham->_Ld); // title. std::map<double,const std::string,std::greater<double> >::const_iterator mit = mres_tmp.begin(); while (mit!=mres_tmp.end()) { mres.insert(std::pair<double,const std::string>((*mit).first,(*mit).second)); // we could do better than this merging... ++mit; } if (!mres.empty()) { // iterate results and merge as possible. mit = mres.begin(); while (mit!=mres.end()) { search_snippet *comp_sp = qc->get_cached_snippet((*mit).second); if (!comp_sp) comp_sp = qc->get_cached_snippet_title((*mit).second.c_str()); if (!comp_sp) { // skip this entry. ++mit; continue; } // Beware: second url (from sp) is the one to be possibly deleted! bool same = content_handler::has_same_content(qc,comp_sp,sp,st); if (same) { search_snippet::merge_snippets(comp_sp,sp); it = snippets.erase(it); delete sp; sp = NULL; break; } ++mit; } } // end if mres empty. if (!sp) continue; } //debug //std::cerr << "new url scanned: " << sp->_url << std::endl; //debug sp->_meta_rank = sp->_engine.size(); sp->_new = false; qc->add_to_unordered_cache(sp); qc->add_to_unordered_cache_title(sp); // lsh. if (content_analysis) { std::string surl = urlmatch::strip_url(sp->_url); qc->_ulsh_ham->add(surl,qc->_lsh_ham->_Ld); std::string lctitle = sp->_title; std::transform(lctitle.begin(),lctitle.end(),lctitle.begin(),tolower); qc->_ulsh_ham->add(lctitle,qc->_lsh_ham->_Ld); } } // end if new. ++it; } // end while. // sort by rank. /*std::stable_sort(snippets.begin(),snippets.end(), search_snippet::max_meta_rank);*/ std::stable_sort(snippets.begin(),snippets.end(), search_snippet::max_seeks_rank); //debug /* std::cerr << "[Debug]: sorted result snippets:\n"; it = snippets.begin(); while(it!=snippets.end()) { (*it)->print(std::cerr); it++; i++; } */ //debug } void sort_rank::score_and_sort_by_similarity(query_context *qc, const char *id_str, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, search_snippet *&ref_sp, std::vector<search_snippet*> &sorted_snippets) throw (sp_exception) { uint32_t id = (uint32_t)strtod(id_str,NULL); ref_sp = qc->get_cached_snippet(id); if (!ref_sp) // this should not happen, unless someone is forcing an url onto a Seeks node. throw sp_exception(WB_ERR_NO_REF_SIM,"cannot find ref id among cached snippets"); ref_sp->set_back_similarity_link(parameters); bool content_analysis = websearch::_wconfig->_content_analysis; const char *ca = miscutil::lookup(parameters,"content_analysis"); if (ca && strcasecmp(ca,"on") == 0) content_analysis = true; if (content_analysis) content_handler::fetch_all_snippets_content_and_features(qc); else content_handler::fetch_all_snippets_summary_and_features(qc); // run similarity analysis and compute scores. try { content_handler::feature_based_similarity_scoring(qc,sorted_snippets.size(), &sorted_snippets.at(0),ref_sp); } catch (sp_exception &e) { throw e; } // sort snippets according to computed scores. std::stable_sort(sorted_snippets.begin(),sorted_snippets.end(),search_snippet::max_seeks_ir); } void sort_rank::group_by_types(query_context *qc, cluster *&clusters, short &K) { /** * grouping is done per file type, the most common being: * 0 - html / html aka webpages (but no wikis) * 1 - wiki * 2 - pdf * 3 - .doc, .pps, & so on aka other types of documents. * 4 - forums * 5 - video file * 6 - tweets * 7 - posts * 8 - revisions * 10 - issues * So for now, K is set to 10. */ K = 10; clusters = new cluster[K]; size_t nsnippets = qc->_cached_snippets.size(); for (size_t i=0; i<nsnippets; i++) { search_snippet *se = qc->_cached_snippets.at(i); if (se->_doc_type == WEBPAGE) { clusters[0].add_point(se->_id,NULL); clusters[0]._label = "Webpages"; // TODO: languages... } else if (se->_doc_type == WIKI) { clusters[1].add_point(se->_id,NULL); clusters[1]._label = "Wikis"; } else if (se->_doc_type == FILE_DOC && se->_file_format == "pdf") { clusters[2].add_point(se->_id,NULL); clusters[2]._label = "PDFs"; } else if (se->_doc_type == FILE_DOC) { clusters[3].add_point(se->_id,NULL); clusters[3]._label = "Other files"; } else if (se->_doc_type == FORUM) { clusters[4].add_point(se->_id,NULL); clusters[4]._label = "Forums"; } else if (se->_doc_type == VIDEO || se->_doc_type == VIDEO_THUMB) { clusters[5].add_point(se->_id,NULL); clusters[5]._label = "Videos"; } else if (se->_doc_type == AUDIO) { clusters[6].add_point(se->_id,NULL); clusters[6]._label = "Audio"; } else if (se->_doc_type == TWEET) { clusters[7].add_point(se->_id,NULL); clusters[7]._label = "Tweets"; } else if (se->_doc_type == POST) { clusters[8].add_point(se->_id,NULL); clusters[8]._label = "posts"; } else if (se->_doc_type == REVISION) { clusters[9].add_point(se->_id,NULL); clusters[9]._label = "Revisions"; } else if (se->_doc_type == ISSUE) { clusters[10].add_point(se->_id,NULL); clusters[10]._label = "Issues"; } } // sort groups by decreasing sizes. std::stable_sort(clusters,clusters+K,cluster::max_size_cluster); } #if defined(PROTOBUF) && defined(TC) void sort_rank::personalize(query_context *qc) { if (!websearch::_cf_plugin) return; cf *cfp = static_cast<cf*>(websearch::_cf_plugin); cfp->personalize(qc); std::stable_sort(qc->_cached_snippets.begin(),qc->_cached_snippets.end(), search_snippet::max_seeks_rank); } void sort_rank::personalized_rank_snippets(query_context *qc, std::vector<search_snippet*> &snippets) throw (sp_exception) { if (!websearch::_cf_plugin) return; static_cast<cf*>(websearch::_cf_plugin)->estimate_ranks(qc->_query,qc->_auto_lang, qc->_page_expansion,snippets); std::stable_sort(snippets.begin(),snippets.end(), search_snippet::max_seeks_rank); } void sort_rank::get_related_queries(query_context *qc) throw (sp_exception) { if (!websearch::_cf_plugin) return; static_cast<cf*>(websearch::_cf_plugin)->get_related_queries(qc->_query,qc->_auto_lang, qc->_page_expansion,qc->_suggestions); } void sort_rank::get_recommended_urls(query_context *qc) throw (sp_exception) { if (!websearch::_cf_plugin) return; static_cast<cf*>(websearch::_cf_plugin)->get_recommended_urls(qc->_query,qc->_auto_lang, qc->_page_expansion, qc->_recommended_snippets); qc->update_recommended_urls(); } #endif } /* end of namespace. */ <|endoftext|>
<commit_before>/* libs/graphics/ports/SkFontHost_fontconfig.cpp ** ** Copyright 2008, Google Inc. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ // ----------------------------------------------------------------------------- // This file provides implementations of the font resolution members of // SkFontHost by using the fontconfig[1] library. Fontconfig is usually found // on Linux systems and handles configuration, parsing and caching issues // involved with enumerating and matching fonts. // // [1] http://fontconfig.org // ----------------------------------------------------------------------------- #include <map> #include <string> #include <fontconfig/fontconfig.h> #include "SkFontHost.h" #include "SkStream.h" // This is an extern from SkFontHost_FreeType SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name); // ----------------------------------------------------------------------------- // The rest of Skia requires that fonts be identified by a unique unsigned id // and that we be able to load them given the id. What we actually get from // fontconfig is the filename of the font so we keep a locked map from // filenames to fileid numbers and back. // // Note that there's also a unique id in the SkTypeface. This is unique over // both filename and style. Thus we encode that id as (fileid << 8) | style. // Although truetype fonts can support multiple faces in a single file, at the // moment Skia doesn't. // ----------------------------------------------------------------------------- static SkMutex global_fc_map_lock; static std::map<std::string, unsigned> global_fc_map; static std::map<unsigned, std::string> global_fc_map_inverted; static std::map<uint32_t, SkTypeface *> global_fc_typefaces; static unsigned global_fc_map_next_id = 0; // This is the maximum size of the font cache. static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB static unsigned UniqueIdToFileId(unsigned uniqueid) { return uniqueid >> 8; } static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid) { return static_cast<SkTypeface::Style>(uniqueid & 0xff); } static unsigned FileIdAndStyleToUniqueId(unsigned fileid, SkTypeface::Style style) { SkASSERT(style & 0xff == style); return (fileid << 8) | static_cast<int>(style); } // ----------------------------------------------------------------------------- // Normally we only return exactly the font asked for. In last-resort cases, // the request is for one of the basic font names "Sans", "Serif" or // "Monospace". This function tells you whether a given request is for such a // fallback. // ----------------------------------------------------------------------------- static bool IsFallbackFontAllowed(const char* request) { return strcmp(request, "Sans") == 0 || strcmp(request, "Serif") == 0 || strcmp(request, "Monospace") == 0; } class FontConfigTypeface : public SkTypeface { public: FontConfigTypeface(Style style, uint32_t id) : SkTypeface(style, id) { } }; // ----------------------------------------------------------------------------- // Find a matching font where @type (one of FC_*) is equal to @value. For a // list of types, see http://fontconfig.org/fontconfig-devel/x19.html#AEN27. // The variable arguments are a list of triples, just like the first three // arguments, and must be NULL terminated. // // For example, // FontMatchString(FC_FILE, FcTypeString, "/usr/share/fonts/myfont.ttf", // NULL); // ----------------------------------------------------------------------------- static FcPattern* FontMatch(const char* type, FcType vtype, const void* value, ...) { va_list ap; va_start(ap, value); FcPattern* pattern = FcPatternCreate(); const char* family_requested = NULL; for (;;) { FcValue fcvalue; fcvalue.type = vtype; switch (vtype) { case FcTypeString: fcvalue.u.s = (FcChar8*) value; break; case FcTypeInteger: fcvalue.u.i = (int)(intptr_t)value; break; default: SkASSERT(!"FontMatch unhandled type"); } FcPatternAdd(pattern, type, fcvalue, 0); if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0) family_requested = (const char*) value; type = va_arg(ap, const char *); if (!type) break; // FcType is promoted to int when passed through ... vtype = static_cast<FcType>(va_arg(ap, int)); value = va_arg(ap, const void *); }; va_end(ap); FcConfigSubstitute(0, pattern, FcMatchPattern); FcDefaultSubstitute(pattern); // Font matching: // CSS often specifies a fallback list of families: // font-family: a, b, c, serif; // However, fontconfig will always do its best to find *a* font when asked // for something so we need a way to tell if the match which it has found is // "good enough" for us. Otherwise, we can return NULL which gets piped up // and lets WebKit know to try the next CSS family name. However, fontconfig // configs allow substitutions (mapping "Arial -> Helvetica" etc) and we // wish to support that. // // Thus, if a specific family is requested we set @family_requested. Then we // record two strings: the family name after config processing and the // family name after resolving. If the two are equal, it's a good match. // // So consider the case where a user has mapped Arial to Helvetica in their // config. // requested family: "Arial" // post_config_family: "Helvetica" // post_match_family: "Helvetica" // -> good match // // and for a missing font: // requested family: "Monaco" // post_config_family: "Monaco" // post_match_family: "Times New Roman" // -> BAD match // // However, we special-case fallback fonts; see IsFallbackFontAllowed(). FcChar8* post_config_family; FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family); FcResult result; FcPattern* match = FcFontMatch(0, pattern, &result); if (!match) { FcPatternDestroy(pattern); return NULL; } FcChar8* post_match_family; FcPatternGetString(match, FC_FAMILY, 0, &post_match_family); const bool family_names_match = !family_requested ? true : strcasecmp((char *)post_config_family, (char *)post_match_family) == 0; FcPatternDestroy(pattern); if (!family_names_match && !IsFallbackFontAllowed(family_requested)) { FcPatternDestroy(match); return NULL; } return match; } // ----------------------------------------------------------------------------- // Check to see if the filename has already been assigned a fileid and, if so, // use it. Otherwise, assign one. Return the resulting fileid. // ----------------------------------------------------------------------------- static unsigned FileIdFromFilename(const char* filename) { SkAutoMutexAcquire ac(global_fc_map_lock); std::map<std::string, unsigned>::const_iterator i = global_fc_map.find(filename); if (i == global_fc_map.end()) { const unsigned fileid = global_fc_map_next_id++; global_fc_map[filename] = fileid; global_fc_map_inverted[fileid] = filename; return fileid; } else { return i->second; } } // static SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace, const char familyName[], SkTypeface::Style style) { const char* resolved_family_name = NULL; FcPattern* face_match = NULL; { SkAutoMutexAcquire ac(global_fc_map_lock); FcInit(); } if (familyFace) { // Here we use the inverted global id map to find the filename from the // SkTypeface object. Given the filename we can ask fontconfig for the // familyname of the font. SkAutoMutexAcquire ac(global_fc_map_lock); const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID()); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; FcInit(); face_match = FontMatch(FC_FILE, FcTypeString, i->second.c_str(), NULL); if (!face_match) return NULL; FcChar8* family; if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) { FcPatternDestroy(face_match); return NULL; } // At this point, @family is pointing into the @face_match object so we // cannot release it yet. resolved_family_name = reinterpret_cast<char*>(family); } else if (familyName) { resolved_family_name = familyName; } else { return NULL; } // At this point, we have a resolved_family_name from somewhere SkASSERT(resolved_family_name); const int bold = style & SkTypeface::kBold ? FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL; const int italic = style & SkTypeface::kItalic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN; FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, resolved_family_name, FC_WEIGHT, FcTypeInteger, bold, FC_SLANT, FcTypeInteger, italic, NULL); if (face_match) FcPatternDestroy(face_match); if (!match) return NULL; FcChar8* filename; if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) { FcPatternDestroy(match); return NULL; } // Now @filename is pointing into @match const unsigned fileid = FileIdFromFilename(reinterpret_cast<char*>(filename)); const unsigned id = FileIdAndStyleToUniqueId(fileid, style); SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id)); FcPatternDestroy(match); { SkAutoMutexAcquire ac(global_fc_map_lock); global_fc_typefaces[id] = typeface; } return typeface; } // static SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream) { SkASSERT(!"SkFontHost::CreateTypefaceFromStream unimplemented"); return NULL; } // static SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[]) { SkASSERT(!"SkFontHost::CreateTypefaceFromFile unimplemented"); return NULL; } // static bool SkFontHost::ValidFontID(SkFontID uniqueID) { SkAutoMutexAcquire ac(global_fc_map_lock); return global_fc_typefaces.find(uniqueID) != global_fc_typefaces.end(); } // static SkStream* SkFontHost::OpenStream(uint32_t id) { SkAutoMutexAcquire ac(global_fc_map_lock); const unsigned fileid = UniqueIdToFileId(id); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; return SkNEW_ARGS(SkFILEStream, (i->second.c_str())); } void SkFontHost::Serialize(const SkTypeface*, SkWStream*) { SkASSERT(!"SkFontHost::Serialize unimplemented"); } SkTypeface* SkFontHost::Deserialize(SkStream* stream) { SkASSERT(!"SkFontHost::Deserialize unimplemented"); return NULL; } // static uint32_t SkFontHost::NextLogicalFont(SkFontID fontID) { // We don't handle font fallback, WebKit does. return 0; } /////////////////////////////////////////////////////////////////////////////// size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar) { if (sizeAllocatedSoFar > kFontCacheMemoryBudget) return sizeAllocatedSoFar - kFontCacheMemoryBudget; else return 0; // nothing to do } <commit_msg>Fix a precedence error in an assert in the fontconfig host.<commit_after>/* libs/graphics/ports/SkFontHost_fontconfig.cpp ** ** Copyright 2008, Google Inc. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ // ----------------------------------------------------------------------------- // This file provides implementations of the font resolution members of // SkFontHost by using the fontconfig[1] library. Fontconfig is usually found // on Linux systems and handles configuration, parsing and caching issues // involved with enumerating and matching fonts. // // [1] http://fontconfig.org // ----------------------------------------------------------------------------- #include <map> #include <string> #include <fontconfig/fontconfig.h> #include "SkFontHost.h" #include "SkStream.h" // This is an extern from SkFontHost_FreeType SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name); // ----------------------------------------------------------------------------- // The rest of Skia requires that fonts be identified by a unique unsigned id // and that we be able to load them given the id. What we actually get from // fontconfig is the filename of the font so we keep a locked map from // filenames to fileid numbers and back. // // Note that there's also a unique id in the SkTypeface. This is unique over // both filename and style. Thus we encode that id as (fileid << 8) | style. // Although truetype fonts can support multiple faces in a single file, at the // moment Skia doesn't. // ----------------------------------------------------------------------------- static SkMutex global_fc_map_lock; static std::map<std::string, unsigned> global_fc_map; static std::map<unsigned, std::string> global_fc_map_inverted; static std::map<uint32_t, SkTypeface *> global_fc_typefaces; static unsigned global_fc_map_next_id = 0; // This is the maximum size of the font cache. static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB static unsigned UniqueIdToFileId(unsigned uniqueid) { return uniqueid >> 8; } static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid) { return static_cast<SkTypeface::Style>(uniqueid & 0xff); } static unsigned FileIdAndStyleToUniqueId(unsigned fileid, SkTypeface::Style style) { SkASSERT((style & 0xff) == style); return (fileid << 8) | static_cast<int>(style); } // ----------------------------------------------------------------------------- // Normally we only return exactly the font asked for. In last-resort cases, // the request is for one of the basic font names "Sans", "Serif" or // "Monospace". This function tells you whether a given request is for such a // fallback. // ----------------------------------------------------------------------------- static bool IsFallbackFontAllowed(const char* request) { return strcmp(request, "Sans") == 0 || strcmp(request, "Serif") == 0 || strcmp(request, "Monospace") == 0; } class FontConfigTypeface : public SkTypeface { public: FontConfigTypeface(Style style, uint32_t id) : SkTypeface(style, id) { } }; // ----------------------------------------------------------------------------- // Find a matching font where @type (one of FC_*) is equal to @value. For a // list of types, see http://fontconfig.org/fontconfig-devel/x19.html#AEN27. // The variable arguments are a list of triples, just like the first three // arguments, and must be NULL terminated. // // For example, // FontMatchString(FC_FILE, FcTypeString, "/usr/share/fonts/myfont.ttf", // NULL); // ----------------------------------------------------------------------------- static FcPattern* FontMatch(const char* type, FcType vtype, const void* value, ...) { va_list ap; va_start(ap, value); FcPattern* pattern = FcPatternCreate(); const char* family_requested = NULL; for (;;) { FcValue fcvalue; fcvalue.type = vtype; switch (vtype) { case FcTypeString: fcvalue.u.s = (FcChar8*) value; break; case FcTypeInteger: fcvalue.u.i = (int)(intptr_t)value; break; default: SkASSERT(!"FontMatch unhandled type"); } FcPatternAdd(pattern, type, fcvalue, 0); if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0) family_requested = (const char*) value; type = va_arg(ap, const char *); if (!type) break; // FcType is promoted to int when passed through ... vtype = static_cast<FcType>(va_arg(ap, int)); value = va_arg(ap, const void *); }; va_end(ap); FcConfigSubstitute(0, pattern, FcMatchPattern); FcDefaultSubstitute(pattern); // Font matching: // CSS often specifies a fallback list of families: // font-family: a, b, c, serif; // However, fontconfig will always do its best to find *a* font when asked // for something so we need a way to tell if the match which it has found is // "good enough" for us. Otherwise, we can return NULL which gets piped up // and lets WebKit know to try the next CSS family name. However, fontconfig // configs allow substitutions (mapping "Arial -> Helvetica" etc) and we // wish to support that. // // Thus, if a specific family is requested we set @family_requested. Then we // record two strings: the family name after config processing and the // family name after resolving. If the two are equal, it's a good match. // // So consider the case where a user has mapped Arial to Helvetica in their // config. // requested family: "Arial" // post_config_family: "Helvetica" // post_match_family: "Helvetica" // -> good match // // and for a missing font: // requested family: "Monaco" // post_config_family: "Monaco" // post_match_family: "Times New Roman" // -> BAD match // // However, we special-case fallback fonts; see IsFallbackFontAllowed(). FcChar8* post_config_family; FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family); FcResult result; FcPattern* match = FcFontMatch(0, pattern, &result); if (!match) { FcPatternDestroy(pattern); return NULL; } FcChar8* post_match_family; FcPatternGetString(match, FC_FAMILY, 0, &post_match_family); const bool family_names_match = !family_requested ? true : strcasecmp((char *)post_config_family, (char *)post_match_family) == 0; FcPatternDestroy(pattern); if (!family_names_match && !IsFallbackFontAllowed(family_requested)) { FcPatternDestroy(match); return NULL; } return match; } // ----------------------------------------------------------------------------- // Check to see if the filename has already been assigned a fileid and, if so, // use it. Otherwise, assign one. Return the resulting fileid. // ----------------------------------------------------------------------------- static unsigned FileIdFromFilename(const char* filename) { SkAutoMutexAcquire ac(global_fc_map_lock); std::map<std::string, unsigned>::const_iterator i = global_fc_map.find(filename); if (i == global_fc_map.end()) { const unsigned fileid = global_fc_map_next_id++; global_fc_map[filename] = fileid; global_fc_map_inverted[fileid] = filename; return fileid; } else { return i->second; } } // static SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace, const char familyName[], SkTypeface::Style style) { const char* resolved_family_name = NULL; FcPattern* face_match = NULL; { SkAutoMutexAcquire ac(global_fc_map_lock); FcInit(); } if (familyFace) { // Here we use the inverted global id map to find the filename from the // SkTypeface object. Given the filename we can ask fontconfig for the // familyname of the font. SkAutoMutexAcquire ac(global_fc_map_lock); const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID()); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; FcInit(); face_match = FontMatch(FC_FILE, FcTypeString, i->second.c_str(), NULL); if (!face_match) return NULL; FcChar8* family; if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) { FcPatternDestroy(face_match); return NULL; } // At this point, @family is pointing into the @face_match object so we // cannot release it yet. resolved_family_name = reinterpret_cast<char*>(family); } else if (familyName) { resolved_family_name = familyName; } else { return NULL; } // At this point, we have a resolved_family_name from somewhere SkASSERT(resolved_family_name); const int bold = style & SkTypeface::kBold ? FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL; const int italic = style & SkTypeface::kItalic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN; FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, resolved_family_name, FC_WEIGHT, FcTypeInteger, bold, FC_SLANT, FcTypeInteger, italic, NULL); if (face_match) FcPatternDestroy(face_match); if (!match) return NULL; FcChar8* filename; if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) { FcPatternDestroy(match); return NULL; } // Now @filename is pointing into @match const unsigned fileid = FileIdFromFilename(reinterpret_cast<char*>(filename)); const unsigned id = FileIdAndStyleToUniqueId(fileid, style); SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id)); FcPatternDestroy(match); { SkAutoMutexAcquire ac(global_fc_map_lock); global_fc_typefaces[id] = typeface; } return typeface; } // static SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream) { SkASSERT(!"SkFontHost::CreateTypefaceFromStream unimplemented"); return NULL; } // static SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[]) { SkASSERT(!"SkFontHost::CreateTypefaceFromFile unimplemented"); return NULL; } // static bool SkFontHost::ValidFontID(SkFontID uniqueID) { SkAutoMutexAcquire ac(global_fc_map_lock); return global_fc_typefaces.find(uniqueID) != global_fc_typefaces.end(); } // static SkStream* SkFontHost::OpenStream(uint32_t id) { SkAutoMutexAcquire ac(global_fc_map_lock); const unsigned fileid = UniqueIdToFileId(id); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; return SkNEW_ARGS(SkFILEStream, (i->second.c_str())); } void SkFontHost::Serialize(const SkTypeface*, SkWStream*) { SkASSERT(!"SkFontHost::Serialize unimplemented"); } SkTypeface* SkFontHost::Deserialize(SkStream* stream) { SkASSERT(!"SkFontHost::Deserialize unimplemented"); return NULL; } // static uint32_t SkFontHost::NextLogicalFont(SkFontID fontID) { // We don't handle font fallback, WebKit does. return 0; } /////////////////////////////////////////////////////////////////////////////// size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar) { if (sizeAllocatedSoFar > kFontCacheMemoryBudget) return sizeAllocatedSoFar - kFontCacheMemoryBudget; else return 0; // nothing to do } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef XENFRONT_HH_ #define XENFRONT_HH_ #include <memory> #include "net.hh" #include "core/sstring.hh" #include "core/xen/gntalloc.hh" std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace); boost::program_options::options_description get_xenfront_net_options_description(); struct netif_tx_request { uint32_t gref; uint16_t offset; struct { uint16_t csum_blank : 1; uint16_t data_validated : 1; uint16_t more_data : 1; uint16_t extra_info : 1; uint16_t pad : 12; } flags; uint16_t id; uint16_t size; }; struct netif_tx_response { uint16_t id; int16_t status; }; struct netif_rx_request { uint16_t id; uint32_t gref; }; struct netif_rx_response { uint16_t id; uint16_t offset; /* Offset in page of start of received packet */ uint16_t flags; /* NETRXF_* */ int16_t status; /* -ve: NETIF_RSP_* ; +ve: Rx'ed response size. */ }; union tx { struct netif_tx_request req; struct netif_tx_response rsp; }; union rx { struct netif_rx_request req; struct netif_rx_response rsp; }; template <typename T> class sring { public: uint32_t req_prod = 0; uint32_t req_event = 1; uint32_t rsp_prod = 0; uint32_t rsp_event = 1; uint8_t pad[48] = { 0 }; T _ring[1]; }; using phys = uint64_t; template <typename T> class front_ring { public: class entries { private: std::array<gntref, 256> _entries; front_ring<T> *_ring; public: entries(front_ring<T> *ring) : _ring(ring) {} gntref& operator[](std::size_t i) { return _entries[_ring->idx(i)]; } friend front_ring; }; protected: uint32_t idx(int i) { return i & (nr_ents - 1); } public: uint32_t req_prod_pvt = 0; uint32_t rsp_cons = 0; static constexpr uint32_t nr_ents = 256; /* FIXME : DYN */ int32_t ref = -1; front_ring(gntref r) : ref(r.xen_id), entries(this) , _sring(static_cast<sring<T> *>(r.page)) { new (_sring) sring<T>(); } future<uint32_t> free_idx(); entries entries; sring<T> *_sring; T& operator[](std::size_t i) { return _sring->_ring[idx(i)]; } }; #endif /* XENFRONT_HH_ */ <commit_msg>xen: simplify front_ring constructor<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef XENFRONT_HH_ #define XENFRONT_HH_ #include <memory> #include "net.hh" #include "core/sstring.hh" #include "core/xen/gntalloc.hh" std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace); boost::program_options::options_description get_xenfront_net_options_description(); struct netif_tx_request { uint32_t gref; uint16_t offset; struct { uint16_t csum_blank : 1; uint16_t data_validated : 1; uint16_t more_data : 1; uint16_t extra_info : 1; uint16_t pad : 12; } flags; uint16_t id; uint16_t size; }; struct netif_tx_response { uint16_t id; int16_t status; }; struct netif_rx_request { uint16_t id; uint32_t gref; }; struct netif_rx_response { uint16_t id; uint16_t offset; /* Offset in page of start of received packet */ uint16_t flags; /* NETRXF_* */ int16_t status; /* -ve: NETIF_RSP_* ; +ve: Rx'ed response size. */ }; union tx { struct netif_tx_request req; struct netif_tx_response rsp; }; union rx { struct netif_rx_request req; struct netif_rx_response rsp; }; template <typename T> class sring { public: uint32_t req_prod = 0; uint32_t req_event = 1; uint32_t rsp_prod = 0; uint32_t rsp_event = 1; uint8_t pad[48] = { 0 }; T _ring[1]; }; using phys = uint64_t; template <typename T> class front_ring { public: class entries { private: std::array<gntref, 256> _entries; front_ring<T> *_ring; public: entries(front_ring<T> *ring) : _ring(ring) {} gntref& operator[](std::size_t i) { return _entries[_ring->idx(i)]; } friend front_ring; }; protected: uint32_t idx(int i) { return i & (nr_ents - 1); } public: uint32_t req_prod_pvt = 0; uint32_t rsp_cons = 0; static constexpr uint32_t nr_ents = 256; /* FIXME : DYN */ int32_t ref = -1; front_ring(gntref r) : ref(r.xen_id), entries(this) , _sring(new (r.page) sring<T>()) { } future<uint32_t> free_idx(); entries entries; sring<T> *_sring; T& operator[](std::size_t i) { return _sring->_ring[idx(i)]; } }; #endif /* XENFRONT_HH_ */ <|endoftext|>
<commit_before>/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) 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. */ /** * \file opt_array_splitting.cpp * * If an array is always dereferenced with a constant index, then * split it apart into its elements, making it more amenable to other * optimization passes. * * This skips uniform/varying arrays, which would need careful * handling due to their ir->location fields tying them to the GL API * and other shader stages. */ #include "ir.h" #include "ir_visitor.h" #include "ir_rvalue_visitor.h" #include "glsl_types.h" static bool debug = false; namespace { namespace opt_array_splitting { class variable_entry : public exec_node { public: variable_entry(ir_variable *var) { this->var = var; this->split = true; this->declaration = false; this->components = NULL; this->mem_ctx = NULL; if (var->type->is_array()) this->size = var->type->length; else this->size = var->type->matrix_columns; } ir_variable *var; /* The key: the variable's pointer. */ unsigned size; /* array length or matrix columns */ /** Whether this array should be split or not. */ bool split; /* If the variable had a decl we can work with in the instruction * stream. We can't do splitting on function arguments, which * don't get this variable set. */ bool declaration; ir_variable **components; /** ralloc_parent(this->var) -- the shader's talloc context. */ void *mem_ctx; }; } /* namespace */ using namespace opt_array_splitting; /** * This class does a walk over the tree, coming up with the set of * variables that could be split by looking to see if they are arrays * that are only ever constant-index dereferenced. */ class ir_array_reference_visitor : public ir_hierarchical_visitor { public: ir_array_reference_visitor(void) { this->mem_ctx = ralloc_context(NULL); this->variable_list.make_empty(); } ~ir_array_reference_visitor(void) { ralloc_free(mem_ctx); } bool get_split_list(exec_list *instructions, bool linked); virtual ir_visitor_status visit(ir_variable *); virtual ir_visitor_status visit(ir_dereference_variable *); virtual ir_visitor_status visit_enter(ir_dereference_array *); virtual ir_visitor_status visit_enter(ir_function_signature *); variable_entry *get_variable_entry(ir_variable *var); /* List of variable_entry */ exec_list variable_list; void *mem_ctx; }; } /* namespace */ variable_entry * ir_array_reference_visitor::get_variable_entry(ir_variable *var) { assert(var); if (var->data.mode != ir_var_auto && var->data.mode != ir_var_temporary) return NULL; if (!(var->type->is_array() || var->type->is_matrix())) return NULL; /* If the array hasn't been sized yet, we can't split it. After * linking, this should be resolved. */ if (var->type->is_unsized_array()) return NULL; foreach_in_list(variable_entry, entry, &this->variable_list) { if (entry->var == var) return entry; } variable_entry *entry = new(mem_ctx) variable_entry(var); this->variable_list.push_tail(entry); return entry; } ir_visitor_status ir_array_reference_visitor::visit(ir_variable *ir) { variable_entry *entry = this->get_variable_entry(ir); if (entry) entry->declaration = true; return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit(ir_dereference_variable *ir) { variable_entry *entry = this->get_variable_entry(ir->var); /* If we made it to here without seeing an ir_dereference_array, * then the dereference of this array didn't have a constant index * (see the visit_continue_with_parent below), so we can't split * the variable. */ if (entry) entry->split = false; return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit_enter(ir_dereference_array *ir) { ir_dereference_variable *deref = ir->array->as_dereference_variable(); if (!deref) return visit_continue; variable_entry *entry = this->get_variable_entry(deref->var); /* If the access to the array has a variable index, we wouldn't * know which split variable this dereference should go to. */ if (entry && !ir->array_index->as_constant()) entry->split = false; return visit_continue_with_parent; } ir_visitor_status ir_array_reference_visitor::visit_enter(ir_function_signature *ir) { /* We don't have logic for array-splitting function arguments, * so just look at the body instructions and not the parameter * declarations. */ visit_list_elements(this, &ir->body); return visit_continue_with_parent; } bool ir_array_reference_visitor::get_split_list(exec_list *instructions, bool linked) { visit_list_elements(this, instructions); /* If the shaders aren't linked yet, we can't mess with global * declarations, which need to be matched by name across shaders. */ if (!linked) { foreach_in_list(ir_instruction, node, instructions) { ir_variable *var = node->as_variable(); if (var) { variable_entry *entry = get_variable_entry(var); if (entry) entry->remove(); } } } /* Trim out variables we found that we can't split. */ foreach_in_list_safe(variable_entry, entry, &variable_list) { if (debug) { printf("array %s@%p: decl %d, split %d\n", entry->var->name, (void *) entry->var, entry->declaration, entry->split); } if (!(entry->declaration && entry->split)) { entry->remove(); } } return !variable_list.is_empty(); } /** * This class rewrites the dereferences of arrays that have been split * to use the newly created ir_variables for each component. */ class ir_array_splitting_visitor : public ir_rvalue_visitor { public: ir_array_splitting_visitor(exec_list *vars) { this->variable_list = vars; } virtual ~ir_array_splitting_visitor() { } virtual ir_visitor_status visit_leave(ir_assignment *); void split_deref(ir_dereference **deref); void handle_rvalue(ir_rvalue **rvalue); variable_entry *get_splitting_entry(ir_variable *var); exec_list *variable_list; }; variable_entry * ir_array_splitting_visitor::get_splitting_entry(ir_variable *var) { assert(var); foreach_in_list(variable_entry, entry, this->variable_list) { if (entry->var == var) { return entry; } } return NULL; } void ir_array_splitting_visitor::split_deref(ir_dereference **deref) { ir_dereference_array *deref_array = (*deref)->as_dereference_array(); if (!deref_array) return; ir_dereference_variable *deref_var = deref_array->array->as_dereference_variable(); if (!deref_var) return; ir_variable *var = deref_var->var; variable_entry *entry = get_splitting_entry(var); if (!entry) return; ir_constant *constant = deref_array->array_index->as_constant(); assert(constant); if (constant->value.i[0] < (int)entry->size) { *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[constant->value.i[0]]); } else { /* There was a constant array access beyond the end of the * array. This might have happened due to constant folding * after the initial parse. This produces an undefined value, * but shouldn't crash. Just give them an uninitialized * variable. */ ir_variable *temp = new(entry->mem_ctx) ir_variable(deref_array->type, "undef", ir_var_temporary); entry->components[0]->insert_before(temp); *deref = new(entry->mem_ctx) ir_dereference_variable(temp); } } void ir_array_splitting_visitor::handle_rvalue(ir_rvalue **rvalue) { if (!*rvalue) return; ir_dereference *deref = (*rvalue)->as_dereference(); if (!deref) return; split_deref(&deref); *rvalue = deref; } ir_visitor_status ir_array_splitting_visitor::visit_leave(ir_assignment *ir) { /* The normal rvalue visitor skips the LHS of assignments, but we * need to process those just the same. */ ir_rvalue *lhs = ir->lhs; handle_rvalue(&lhs); ir->lhs = lhs->as_dereference(); ir->lhs->accept(this); handle_rvalue(&ir->rhs); ir->rhs->accept(this); if (ir->condition) { handle_rvalue(&ir->condition); ir->condition->accept(this); } return visit_continue; } bool optimize_split_arrays(exec_list *instructions, bool linked) { ir_array_reference_visitor refs; if (!refs.get_split_list(instructions, linked)) return false; void *mem_ctx = ralloc_context(NULL); /* Replace the decls of the arrays to be split with their split * components. */ foreach_in_list(variable_entry, entry, &refs.variable_list) { const struct glsl_type *type = entry->var->type; const struct glsl_type *subtype; if (type->is_matrix()) subtype = type->column_type(); else subtype = type->fields.array; entry->mem_ctx = ralloc_parent(entry->var); entry->components = ralloc_array(mem_ctx, ir_variable *, entry->size); for (unsigned int i = 0; i < entry->size; i++) { const char *name = ralloc_asprintf(mem_ctx, "%s_%d", entry->var->name, i); entry->components[i] = new(entry->mem_ctx) ir_variable(subtype, name, ir_var_temporary); entry->var->insert_before(entry->components[i]); } entry->var->remove(); } ir_array_splitting_visitor split(&refs.variable_list); visit_list_elements(&split, instructions); if (debug) _mesa_print_ir(stdout, instructions, NULL); ralloc_free(mem_ctx); return true; } <commit_msg>glsl: Fix crash due to negative array index<commit_after>/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) 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. */ /** * \file opt_array_splitting.cpp * * If an array is always dereferenced with a constant index, then * split it apart into its elements, making it more amenable to other * optimization passes. * * This skips uniform/varying arrays, which would need careful * handling due to their ir->location fields tying them to the GL API * and other shader stages. */ #include "ir.h" #include "ir_visitor.h" #include "ir_rvalue_visitor.h" #include "glsl_types.h" static bool debug = false; namespace { namespace opt_array_splitting { class variable_entry : public exec_node { public: variable_entry(ir_variable *var) { this->var = var; this->split = true; this->declaration = false; this->components = NULL; this->mem_ctx = NULL; if (var->type->is_array()) this->size = var->type->length; else this->size = var->type->matrix_columns; } ir_variable *var; /* The key: the variable's pointer. */ unsigned size; /* array length or matrix columns */ /** Whether this array should be split or not. */ bool split; /* If the variable had a decl we can work with in the instruction * stream. We can't do splitting on function arguments, which * don't get this variable set. */ bool declaration; ir_variable **components; /** ralloc_parent(this->var) -- the shader's talloc context. */ void *mem_ctx; }; } /* namespace */ using namespace opt_array_splitting; /** * This class does a walk over the tree, coming up with the set of * variables that could be split by looking to see if they are arrays * that are only ever constant-index dereferenced. */ class ir_array_reference_visitor : public ir_hierarchical_visitor { public: ir_array_reference_visitor(void) { this->mem_ctx = ralloc_context(NULL); this->variable_list.make_empty(); } ~ir_array_reference_visitor(void) { ralloc_free(mem_ctx); } bool get_split_list(exec_list *instructions, bool linked); virtual ir_visitor_status visit(ir_variable *); virtual ir_visitor_status visit(ir_dereference_variable *); virtual ir_visitor_status visit_enter(ir_dereference_array *); virtual ir_visitor_status visit_enter(ir_function_signature *); variable_entry *get_variable_entry(ir_variable *var); /* List of variable_entry */ exec_list variable_list; void *mem_ctx; }; } /* namespace */ variable_entry * ir_array_reference_visitor::get_variable_entry(ir_variable *var) { assert(var); if (var->data.mode != ir_var_auto && var->data.mode != ir_var_temporary) return NULL; if (!(var->type->is_array() || var->type->is_matrix())) return NULL; /* If the array hasn't been sized yet, we can't split it. After * linking, this should be resolved. */ if (var->type->is_unsized_array()) return NULL; foreach_in_list(variable_entry, entry, &this->variable_list) { if (entry->var == var) return entry; } variable_entry *entry = new(mem_ctx) variable_entry(var); this->variable_list.push_tail(entry); return entry; } ir_visitor_status ir_array_reference_visitor::visit(ir_variable *ir) { variable_entry *entry = this->get_variable_entry(ir); if (entry) entry->declaration = true; return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit(ir_dereference_variable *ir) { variable_entry *entry = this->get_variable_entry(ir->var); /* If we made it to here without seeing an ir_dereference_array, * then the dereference of this array didn't have a constant index * (see the visit_continue_with_parent below), so we can't split * the variable. */ if (entry) entry->split = false; return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit_enter(ir_dereference_array *ir) { ir_dereference_variable *deref = ir->array->as_dereference_variable(); if (!deref) return visit_continue; variable_entry *entry = this->get_variable_entry(deref->var); /* If the access to the array has a variable index, we wouldn't * know which split variable this dereference should go to. */ if (entry && !ir->array_index->as_constant()) entry->split = false; return visit_continue_with_parent; } ir_visitor_status ir_array_reference_visitor::visit_enter(ir_function_signature *ir) { /* We don't have logic for array-splitting function arguments, * so just look at the body instructions and not the parameter * declarations. */ visit_list_elements(this, &ir->body); return visit_continue_with_parent; } bool ir_array_reference_visitor::get_split_list(exec_list *instructions, bool linked) { visit_list_elements(this, instructions); /* If the shaders aren't linked yet, we can't mess with global * declarations, which need to be matched by name across shaders. */ if (!linked) { foreach_in_list(ir_instruction, node, instructions) { ir_variable *var = node->as_variable(); if (var) { variable_entry *entry = get_variable_entry(var); if (entry) entry->remove(); } } } /* Trim out variables we found that we can't split. */ foreach_in_list_safe(variable_entry, entry, &variable_list) { if (debug) { printf("array %s@%p: decl %d, split %d\n", entry->var->name, (void *) entry->var, entry->declaration, entry->split); } if (!(entry->declaration && entry->split)) { entry->remove(); } } return !variable_list.is_empty(); } /** * This class rewrites the dereferences of arrays that have been split * to use the newly created ir_variables for each component. */ class ir_array_splitting_visitor : public ir_rvalue_visitor { public: ir_array_splitting_visitor(exec_list *vars) { this->variable_list = vars; } virtual ~ir_array_splitting_visitor() { } virtual ir_visitor_status visit_leave(ir_assignment *); void split_deref(ir_dereference **deref); void handle_rvalue(ir_rvalue **rvalue); variable_entry *get_splitting_entry(ir_variable *var); exec_list *variable_list; }; variable_entry * ir_array_splitting_visitor::get_splitting_entry(ir_variable *var) { assert(var); foreach_in_list(variable_entry, entry, this->variable_list) { if (entry->var == var) { return entry; } } return NULL; } void ir_array_splitting_visitor::split_deref(ir_dereference **deref) { ir_dereference_array *deref_array = (*deref)->as_dereference_array(); if (!deref_array) return; ir_dereference_variable *deref_var = deref_array->array->as_dereference_variable(); if (!deref_var) return; ir_variable *var = deref_var->var; variable_entry *entry = get_splitting_entry(var); if (!entry) return; ir_constant *constant = deref_array->array_index->as_constant(); assert(constant); if (constant->value.i[0] >= 0 && constant->value.i[0] < (int)entry->size) { *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[constant->value.i[0]]); } else { /* There was a constant array access beyond the end of the * array. This might have happened due to constant folding * after the initial parse. This produces an undefined value, * but shouldn't crash. Just give them an uninitialized * variable. */ ir_variable *temp = new(entry->mem_ctx) ir_variable(deref_array->type, "undef", ir_var_temporary); entry->components[0]->insert_before(temp); *deref = new(entry->mem_ctx) ir_dereference_variable(temp); } } void ir_array_splitting_visitor::handle_rvalue(ir_rvalue **rvalue) { if (!*rvalue) return; ir_dereference *deref = (*rvalue)->as_dereference(); if (!deref) return; split_deref(&deref); *rvalue = deref; } ir_visitor_status ir_array_splitting_visitor::visit_leave(ir_assignment *ir) { /* The normal rvalue visitor skips the LHS of assignments, but we * need to process those just the same. */ ir_rvalue *lhs = ir->lhs; handle_rvalue(&lhs); ir->lhs = lhs->as_dereference(); ir->lhs->accept(this); handle_rvalue(&ir->rhs); ir->rhs->accept(this); if (ir->condition) { handle_rvalue(&ir->condition); ir->condition->accept(this); } return visit_continue; } bool optimize_split_arrays(exec_list *instructions, bool linked) { ir_array_reference_visitor refs; if (!refs.get_split_list(instructions, linked)) return false; void *mem_ctx = ralloc_context(NULL); /* Replace the decls of the arrays to be split with their split * components. */ foreach_in_list(variable_entry, entry, &refs.variable_list) { const struct glsl_type *type = entry->var->type; const struct glsl_type *subtype; if (type->is_matrix()) subtype = type->column_type(); else subtype = type->fields.array; entry->mem_ctx = ralloc_parent(entry->var); entry->components = ralloc_array(mem_ctx, ir_variable *, entry->size); for (unsigned int i = 0; i < entry->size; i++) { const char *name = ralloc_asprintf(mem_ctx, "%s_%d", entry->var->name, i); entry->components[i] = new(entry->mem_ctx) ir_variable(subtype, name, ir_var_temporary); entry->var->insert_before(entry->components[i]); } entry->var->remove(); } ir_array_splitting_visitor split(&refs.variable_list); visit_list_elements(&split, instructions); if (debug) _mesa_print_ir(stdout, instructions, NULL); ralloc_free(mem_ctx); return true; } <|endoftext|>
<commit_before>// // Copyright (c) 2017, Boris Popov <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // #include "Semaphore.hpp" #include "ErrorBuilder.hpp" ////////////////////////////////////////////////////////////////// linux::posix:: Semaphore::Semaphore(const Name n, const UNLINK_AFTER_DESTROY d, const OpenOptions oo, unsigned int v): name(n), destroy(d), options(oo), value(v), semaphore(nullptr) { return; } void linux::posix::Semaphore::close() { if (semaphore == SEM_FAILED) return; if (semaphore == nullptr) return; int res = sem_close(semaphore); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } semaphore = nullptr; } linux::posix:: Semaphore::~Semaphore() { if (semaphore == SEM_FAILED) return; if (semaphore == nullptr) return; sem_close(semaphore); if (destroy) sem_unlink(name.c_str()); } ////////////////////////////////////////////////////////////////// <commit_msg>add Semaphore::open<commit_after>// // Copyright (c) 2017, Boris Popov <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // #include "Semaphore.hpp" #include "ErrorBuilder.hpp" ////////////////////////////////////////////////////////////////// linux::posix:: Semaphore::Semaphore(const Name n, const UNLINK_AFTER_DESTROY d, const OpenOptions oo, unsigned int v): name(n), destroy(d), options(oo), value(v), semaphore(nullptr) { return; } void linux::posix::Semaphore::open() { semaphore = sem_open(name.c_str(), options.get_oflag().get(), options.get_mode().get(), value); if (semaphore == SEM_FAILED) { int e = errno; ErrorBuilder eb; throw eb.build(e); } } void linux::posix::Semaphore::close() { if (semaphore == SEM_FAILED) return; if (semaphore == nullptr) return; int res = sem_close(semaphore); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } semaphore = nullptr; } linux::posix:: Semaphore::~Semaphore() { if (semaphore == SEM_FAILED) return; if (semaphore == nullptr) return; sem_close(semaphore); if (destroy) sem_unlink(name.c_str()); } ////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include "tidyup_state_creators/stateCreatorRobotPoseGrounding.h" #include <pluginlib/class_list_macros.h> #include <visualization_msgs/MarkerArray.h> #include <angles/angles.h> #include <symbolic_planning_utils/extractPose.h> #include <symbolic_planning_utils/load_tables.h> #include <symbolic_planning_utils/moveGroupInterface.h> #include <ros/package.h> PLUGINLIB_EXPORT_CLASS(tidyup_state_creators::StateCreatorRobotPoseGrounding, continual_planning_executive::StateCreator) namespace tidyup_state_creators { StateCreatorRobotPoseGrounding::StateCreatorRobotPoseGrounding() { ros::NodeHandle nhPriv("~"); ros::NodeHandle nh; nhPriv.param("nav_target_tolerance_xy", _goalToleranceXY, 0.15); nhPriv.param("nav_target_tolerance_yaw", _goalToleranceYaw, 0.26); // corresponds 15deg bool relative; nhPriv.param("nav_target_tolerance_relative_to_move_base", relative, false); if (relative) { // relative mode: 1. get the namespace for base_local_planner std::string base_local_planner_ns; if (!nhPriv.getParam("nav_base_local_planner_ns", base_local_planner_ns)) { ROS_WARN( "nav_target_tolerance_relative_to_move_base set, but nav_base_local_planner_ns not set - trying to estimate"); std::string local_planner; if (!nh.getParam("move_base_node/base_local_planner", local_planner) && !nh.getParam("move_base/base_local_planner", local_planner)) { ROS_ERROR( "move_base(_node)/base_local_planner not set - falling back to absolute mode."); } else { // dwa_local_planner/DWAPlannerROS -> DWAPlannerROS std::string::size_type x = local_planner.find_last_of("/"); if (x == std::string::npos) base_local_planner_ns = local_planner; else base_local_planner_ns = local_planner.substr(x + 1); ROS_INFO("Estimated base_local_planner_ns to %s.", base_local_planner_ns.c_str()); } } if (!base_local_planner_ns.empty()) { // success: 2. get the xy_goal_tolerance double move_base_tol_xy; if (!nh.getParam(base_local_planner_ns + "/xy_goal_tolerance", move_base_tol_xy)) { ROS_ERROR_STREAM( "nav_target_tolerance_relative_to_move_base was true, but " << (base_local_planner_ns + "/xy_goal_tolerance") << " was not set" << " - falling back to absolute mode"); } else { // 2. add move_base's tolerance to our relative tolerance _goalToleranceXY += move_base_tol_xy; } double move_base_tol_yaw; if (!nh.getParam(base_local_planner_ns + "/yaw_goal_tolerance", move_base_tol_yaw)) { ROS_ERROR_STREAM( "nav_target_tolerance_relative_to_move_base was true, but " << (base_local_planner_ns + "/yaw_goal_tolerance") << " was not set" << " - falling back to absolute mode"); } else { // 2. add move_base's tolerance to our relative tolerance _goalToleranceYaw += move_base_tol_yaw; } } } ROS_INFO("Tolerance for accepting nav goals set to %f m, %f deg.", _goalToleranceXY, angles::to_degrees(_goalToleranceYaw)); // LOAD Inverse Capability Maps // first load tables from tables.dat file // load table pose std::vector<symbolic_planning_utils::LoadTables::TableLocation> tables; if (!symbolic_planning_utils::LoadTables::getTables(tables)) { ROS_ERROR("StateCreatorRobotPoseGrounding::%s: Could not load tables", __func__); return; } // store table names and the corresponding inv_reach_map into a member variable for (size_t i = 0; i < tables.size(); i++) { const std::string& tableName = tables[i].name; // read path to inverse reachability maps from param std::string package, relative_path; if (!nh.getParam("continual_planning_executive/inverse_reachability_maps/" + tableName + "/package", package)) { ROS_ERROR("StateCreatorRobotPoseGrounding::%s: Could not load package for surface: %s", __func__, tableName.c_str()); continue; } if (!nh.getParam("continual_planning_executive/inverse_reachability_maps/" + tableName + "/path", relative_path)) { ROS_ERROR("StateCreatorRobotPoseGrounding::%s: Could not load relative path for surface: %s", __func__, tableName.c_str()); continue; } std::string pkg_path = ros::package::getPath(package); std::string path = pkg_path + "/" + relative_path; // store inverse capability maps into global variable InverseCapabilityOcTree* tree = InverseCapabilityOcTree::readFile(path); std::pair<std::string, InverseCapabilityOcTree*> icm = std::make_pair(tableName, tree); inv_cap_maps_.insert(icm); } } StateCreatorRobotPoseGrounding::~StateCreatorRobotPoseGrounding() { } void StateCreatorRobotPoseGrounding::initialize( const std::deque<std::string> & arguments) { ROS_ASSERT(arguments.size() == 5); robot_x_ = arguments[0]; // robot-x robot_y_ = arguments[1]; // robot-y robot_theta_ = arguments[2]; // robot-theta robot_torso_position_ = arguments[3]; // robot-torso-position prediate_robot_near_table_ = arguments[4]; // robot-near-table torso_group_ = symbolic_planning_utils::MoveGroupInterface::getInstance()->getTorsoGroup(); } bool StateCreatorRobotPoseGrounding::fillState(SymbolicState & state) { tf::StampedTransform transform; try { tf_.lookupTransform("/map", "/base_link", ros::Time(0), transform); } catch (tf::TransformException& ex) { ROS_ERROR("%s", ex.what()); return false; } // 1. Update real robot pose state.setNumericalFluent(robot_x_, "", transform.getOrigin().x()); state.setNumericalFluent(robot_y_, "", transform.getOrigin().y()); state.setNumericalFluent(robot_theta_, "", tf::getYaw(transform.getRotation())); const std::vector<double>& jointValues = torso_group_->getCurrentJointValues(); ROS_ASSERT(jointValues.size() == 1); state.setNumericalFluent(robot_torso_position_, "", jointValues[0]); // 2. Set robot-near-table predicate if appropriate string table_name; geometry_msgs::PoseStamped table_pose; tf::StampedTransform transform_map_torso; try { tf_.lookupTransform("/map", "/torso_lift_link", ros::Time(0), transform_map_torso); } catch (tf::TransformException& ex) { ROS_ERROR("%s", ex.what()); return false; } pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> targets = state.getTypedObjects().equal_range("table"); for (SymbolicState::TypedObjectConstIterator it = targets.first; it != targets.second; it++) { // it->first = objectType, it->second = ObjectName table_name = it->second; // fetch table pose from symbolic state if (!symbolic_planning_utils::extractPoseStampedFromSymbolicState(state, table_name, table_pose)) { ROS_ERROR("StateCreatorRobotPoseGrounding::%s: could not extract pose for target object: %s.", __func__, table_name.c_str()); continue; } ROS_ASSERT(table_pose.header.frame_id == "/map"); InverseCapabilityOcTree* tree = inv_cap_maps_[table_name]; ROS_ASSERT(tree); // fetch torso pose and convert into table frame tf::Pose transform_map_table, transform_table_torso; tf::poseMsgToTF(table_pose.pose, transform_map_table); transform_table_torso = transform_map_table.inverseTimes(transform_map_torso); // tf::Pose torso_table = transformTorsoInTableFrame(table_pose); // geometry_msgs::Pose debug; // tf::poseTFToMsg(torso_table, debug); // ROS_INFO_STREAM("StateCreatorRobotPoseGrounding::" << __func__ << ": " << debug); // look if there is a match in inv cap map InverseCapability inv = tree->getNodeInverseCapability(transform_table_torso.getOrigin().x(), transform_table_torso.getOrigin().y(), transform_table_torso.getOrigin().z()); const std::map<double, double>& thetas = inv.getThetasPercent(); // if there exists a theta, means we have an inverse reachability index, // indicating that a part of the table can be reached -> we are close to table if (thetas.size() > 0) { ROS_INFO("StateCreatorRobotPoseGrounding::%s: Robot is near '%s' !", __func__, table_name.c_str()); state.setBooleanPredicate(prediate_robot_near_table_, table_name, true); } else state.setBooleanPredicate(prediate_robot_near_table_, table_name, false); } // // 2. Set robot-near-table predicate if appropriate // // if robot is closer than 1m from table, than set predicate // // TODO: use inv reach maps! // string table_name; // geometry_msgs::PoseStamped table_pose; // double table_radius = 1.0; // // pair<SymbolicState::TypedObjectConstIterator, // SymbolicState::TypedObjectConstIterator> targets = // state.getTypedObjects().equal_range("table"); // for (SymbolicState::TypedObjectConstIterator it = targets.first; // it != targets.second; it++) // { // // it->first = objectType, it->second = ObjectName // table_name = it->second; // // // fetch table pose from symbolic state // if (!symbolic_planning_utils::extractPoseStampedFromSymbolicState(state, // table_name, table_pose)) // { // ROS_ERROR("%s: could not extract pose for target object: %s.", // __func__, table_name.c_str()); // continue; // } // // // FIXME: replace with ros_assertion? // if (table_pose.header.frame_id != "/map") // { // ROS_ERROR("Target pose %s had frame-id: %s - should be /map.", // table_name.c_str(), table_pose.header.frame_id.c_str()); // continue; // } // // // compute dXY between current pose and table // tf::Transform targetTransform; //(btQuaternion(qx, qy, qz, qw), btVector3(posX, posY, 0.0)); // tf::poseMsgToTF(table_pose.pose, targetTransform); // tf::Transform deltaTransform = targetTransform.inverseTimes(transform); // // double dDist = hypot(deltaTransform.getOrigin().x(), // deltaTransform.getOrigin().y()); // // if (dDist < table_radius) // { // ROS_INFO("Robot is near table: %s !", table_name.c_str()); // state.setBooleanPredicate(prediate_robot_near_table_, table_name, true); // } // } return true; } tf::Pose StateCreatorRobotPoseGrounding::transformTorsoInTableFrame(const geometry_msgs::PoseStamped& table) { tf::StampedTransform transform_map_torso; try { tf_.lookupTransform("/map", "/torso_lift_link", ros::Time(0), transform_map_torso); } catch (tf::TransformException& ex) { ROS_ERROR("%s", ex.what()); } tf::Pose transform_map_table, transform_table_torso; tf::poseMsgToTF(table.pose, transform_map_table); transform_table_torso = transform_map_table.inverseTimes(transform_map_torso); return transform_table_torso; } }; // namespace tidyup_state_creators <commit_msg>removed near table predicate from state creator, since a module checks this now<commit_after>#include "tidyup_state_creators/stateCreatorRobotPoseGrounding.h" #include <pluginlib/class_list_macros.h> #include <visualization_msgs/MarkerArray.h> #include <angles/angles.h> #include <symbolic_planning_utils/extractPose.h> #include <symbolic_planning_utils/load_tables.h> #include <symbolic_planning_utils/moveGroupInterface.h> #include <ros/package.h> PLUGINLIB_EXPORT_CLASS(tidyup_state_creators::StateCreatorRobotPoseGrounding, continual_planning_executive::StateCreator) namespace tidyup_state_creators { StateCreatorRobotPoseGrounding::StateCreatorRobotPoseGrounding() { ros::NodeHandle nhPriv("~"); ros::NodeHandle nh; nhPriv.param("nav_target_tolerance_xy", _goalToleranceXY, 0.15); nhPriv.param("nav_target_tolerance_yaw", _goalToleranceYaw, 0.26); // corresponds 15deg bool relative; nhPriv.param("nav_target_tolerance_relative_to_move_base", relative, false); if (relative) { // relative mode: 1. get the namespace for base_local_planner std::string base_local_planner_ns; if (!nhPriv.getParam("nav_base_local_planner_ns", base_local_planner_ns)) { ROS_WARN("nav_target_tolerance_relative_to_move_base set, but nav_base_local_planner_ns not set - trying to estimate"); std::string local_planner; if (!nh.getParam("move_base_node/base_local_planner", local_planner) && !nh.getParam("move_base/base_local_planner", local_planner)) { ROS_ERROR("move_base(_node)/base_local_planner not set - falling back to absolute mode."); } else { // dwa_local_planner/DWAPlannerROS -> DWAPlannerROS std::string::size_type x = local_planner.find_last_of("/"); if (x == std::string::npos) base_local_planner_ns = local_planner; else base_local_planner_ns = local_planner.substr(x + 1); ROS_INFO("Estimated base_local_planner_ns to %s.", base_local_planner_ns.c_str()); } } if (!base_local_planner_ns.empty()) { // success: 2. get the xy_goal_tolerance double move_base_tol_xy; if (!nh.getParam(base_local_planner_ns + "/xy_goal_tolerance", move_base_tol_xy)) { ROS_ERROR_STREAM( "nav_target_tolerance_relative_to_move_base was true, but " << (base_local_planner_ns + "/xy_goal_tolerance") << " was not set" << " - falling back to absolute mode"); } else { // 2. add move_base's tolerance to our relative tolerance _goalToleranceXY += move_base_tol_xy; } double move_base_tol_yaw; if (!nh.getParam(base_local_planner_ns + "/yaw_goal_tolerance", move_base_tol_yaw)) { ROS_ERROR_STREAM( "nav_target_tolerance_relative_to_move_base was true, but " << (base_local_planner_ns + "/yaw_goal_tolerance") << " was not set" << " - falling back to absolute mode"); } else { // 2. add move_base's tolerance to our relative tolerance _goalToleranceYaw += move_base_tol_yaw; } } } ROS_INFO("Tolerance for accepting nav goals set to %f m, %f deg.", _goalToleranceXY, angles::to_degrees(_goalToleranceYaw)); // LOAD Inverse Capability Maps // first load tables from tables.dat file // load table pose std::vector<symbolic_planning_utils::LoadTables::TableLocation> tables; if (!symbolic_planning_utils::LoadTables::getTables(tables)) { ROS_ERROR("StateCreatorRobotPoseGrounding::%s: Could not load tables", __func__); return; } // store table names and the corresponding inv_reach_map into a member variable for (size_t i = 0; i < tables.size(); i++) { const std::string& tableName = tables[i].name; // read path to inverse reachability maps from param std::string package, relative_path; if (!nh.getParam("continual_planning_executive/inverse_reachability_maps/" + tableName + "/package", package)) { ROS_ERROR("StateCreatorRobotPoseGrounding::%s: Could not load package for surface: %s", __func__, tableName.c_str()); continue; } if (!nh.getParam("continual_planning_executive/inverse_reachability_maps/" + tableName + "/path", relative_path)) { ROS_ERROR("StateCreatorRobotPoseGrounding::%s: Could not load relative path for surface: %s", __func__, tableName.c_str()); continue; } std::string pkg_path = ros::package::getPath(package); std::string path = pkg_path + "/" + relative_path; // store inverse capability maps into global variable InverseCapabilityOcTree* tree = InverseCapabilityOcTree::readFile(path); std::pair<std::string, InverseCapabilityOcTree*> icm = std::make_pair(tableName, tree); inv_cap_maps_.insert(icm); } } StateCreatorRobotPoseGrounding::~StateCreatorRobotPoseGrounding() { } void StateCreatorRobotPoseGrounding::initialize( const std::deque<std::string> & arguments) { ROS_ASSERT(arguments.size() == 5); robot_x_ = arguments[0]; // robot-x robot_y_ = arguments[1]; // robot-y robot_theta_ = arguments[2]; // robot-theta robot_torso_position_ = arguments[3]; // robot-torso-position prediate_robot_near_table_ = arguments[4]; // robot-near-table torso_group_ = symbolic_planning_utils::MoveGroupInterface::getInstance()->getTorsoGroup(); } bool StateCreatorRobotPoseGrounding::fillState(SymbolicState & state) { tf::StampedTransform transform; try { tf_.lookupTransform("/map", "/base_link", ros::Time(0), transform); } catch (tf::TransformException& ex) { ROS_ERROR("%s", ex.what()); return false; } // 1. Update real robot pose state.setNumericalFluent(robot_x_, "", transform.getOrigin().x()); state.setNumericalFluent(robot_y_, "", transform.getOrigin().y()); state.setNumericalFluent(robot_theta_, "", tf::getYaw(transform.getRotation())); const std::vector<double>& jointValues = torso_group_->getCurrentJointValues(); ROS_ASSERT(jointValues.size() == 1); state.setNumericalFluent(robot_torso_position_, "", jointValues[0]); // // 2. Set robot-near-table predicate if appropriate // string table_name; // geometry_msgs::PoseStamped table_pose; // tf::StampedTransform transform_map_torso; // try // { // tf_.lookupTransform("/map", "/torso_lift_link", ros::Time(0), transform_map_torso); // } catch (tf::TransformException& ex) // { // ROS_ERROR("%s", ex.what()); // return false; // } // // pair<SymbolicState::TypedObjectConstIterator, // SymbolicState::TypedObjectConstIterator> targets = // state.getTypedObjects().equal_range("table"); // for (SymbolicState::TypedObjectConstIterator it = targets.first; // it != targets.second; it++) // { // // it->first = objectType, it->second = ObjectName // table_name = it->second; // // // fetch table pose from symbolic state // if (!symbolic_planning_utils::extractPoseStampedFromSymbolicState(state, // table_name, table_pose)) // { // ROS_ERROR("StateCreatorRobotPoseGrounding::%s: could not extract pose for target object: %s.", // __func__, table_name.c_str()); // continue; // } // // ROS_ASSERT(table_pose.header.frame_id == "/map"); // if (inv_cap_maps_.find(table_name) == inv_cap_maps_.end()) // { // ROS_ERROR_STREAM("StateCreatorRobotPoseGrounding::"<<__func__<<": could not load inverse reachability map for "<<table_name); // continue; // } // InverseCapabilityOcTree* tree = inv_cap_maps_[table_name]; // ROS_ASSERT(tree); // // // fetch torso pose and convert into table frame // tf::Pose transform_map_table, transform_table_torso; // tf::poseMsgToTF(table_pose.pose, transform_map_table); // // transform_table_torso = transform_map_table.inverseTimes(transform_map_torso); //// tf::Pose torso_table = transformTorsoInTableFrame(table_pose); // //// geometry_msgs::Pose debug; //// tf::poseTFToMsg(torso_table, debug); //// ROS_INFO_STREAM("StateCreatorRobotPoseGrounding::" << __func__ << ": " << debug); // // // look if there is a match in inv cap map // InverseCapability inv = tree->getNodeInverseCapability(transform_table_torso.getOrigin().x(), // transform_table_torso.getOrigin().y(), // transform_table_torso.getOrigin().z()); // // const std::map<double, double>& thetas = inv.getThetasPercent(); // // // if there exists a theta, means we have an inverse reachability index, // // indicating that a part of the table can be reached -> we are close to table // if (thetas.size() > 0) // { // ROS_INFO("StateCreatorRobotPoseGrounding::%s: Robot is near '%s' !", __func__, table_name.c_str()); // state.setBooleanPredicate(prediate_robot_near_table_, table_name, true); // } // else // state.setBooleanPredicate(prediate_robot_near_table_, table_name, false); // } return true; } tf::Pose StateCreatorRobotPoseGrounding::transformTorsoInTableFrame(const geometry_msgs::PoseStamped& table) { tf::StampedTransform transform_map_torso; try { tf_.lookupTransform("/map", "/torso_lift_link", ros::Time(0), transform_map_torso); } catch (tf::TransformException& ex) { ROS_ERROR("%s", ex.what()); } tf::Pose transform_map_table, transform_table_torso; tf::poseMsgToTF(table.pose, transform_map_table); transform_table_torso = transform_map_table.inverseTimes(transform_map_torso); return transform_table_torso; } }; // namespace tidyup_state_creators <|endoftext|>
<commit_before>// //// libavg - Media Playback Engine. //// Copyright (C) 2003-2011 Ulrich von Zadow //// //// 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 //// //// Current versions can be found at www.libavg.de //// #include "GPUHueSatFilter.h" #include "ShaderRegistry.h" #include "../base/ObjectCounter.h" #include "../base/Logger.h" #define SHADERID_HSL_COLOR "HSL_COLOR" using namespace std; namespace avg { GPUHueSatFilter::GPUHueSatFilter(const IntPoint& size, PixelFormat pf, bool bStandalone) : GPUFilter(pf, B8G8R8A8, bStandalone, 2), m_LightnessOffset(0.0), m_Hue(0.0), m_Saturation(0.0) { ObjectCounter::get()->incRef(&typeid(*this)); setDimensions(size); initShader(); } GPUHueSatFilter::~GPUHueSatFilter() { ObjectCounter::get()->decRef(&typeid(*this)); } void GPUHueSatFilter::setParams(int hue, int saturation, int light_add, bool colorize) { m_Hue = float(hue); m_Saturation = saturation / 100.0f; m_LightnessOffset = light_add / 100.0f; m_bColorize = colorize; } void GPUHueSatFilter::applyOnGPU(GLTexturePtr pSrcTex) { OGLShaderPtr pShader = getShader(SHADERID_HSL_COLOR); glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); pShader->activate(); pShader->setUniformFloatParam("hue", m_Hue); pShader->setUniformFloatParam("sat", m_Saturation); pShader->setUniformFloatParam("l_offset", m_LightnessOffset); pShader->setUniformIntParam("b_colorize", (int)m_bColorize); pShader->setUniformIntParam("texture", 0); draw(pSrcTex); glproc::UseProgramObject(0); } void GPUHueSatFilter::initShader() { string sProgramHead = "const vec3 lumCoeff = vec3(0.2125, 0.7154, 0.0721);\n" "const vec3 white = vec3(1.0, 1.0, 1.0);\n" "const vec3 black = vec3(0.0, 0.0, 0.0);\n" "uniform sampler2D texture;\n" "uniform float hue;\n" "uniform float sat;\n" "uniform float l_offset;\n" "uniform bool b_colorize;\n" + getStdShaderCode() ; string sProgram = sProgramHead + "void main(void)\n" "{\n" " float tmp;\n" " float s;\n" " float l;\n" " float h;\n" " vec4 tex = texture2D(texture, gl_TexCoord[0].st);\n" " rgb2hsl(tex, tmp, s, l);\n" " if(b_colorize){\n" " h = hue;\n" " s = sat;\n" " }\n" " else{\n" " h = hue+tmp;\n" " }\n" " vec4 rgbTex = vec4(hsl2rgb(mod(h, 360.0), s, l), tex.a);\n" //Saturate in rgb - space to imitate photoshop filter " if(!b_colorize){ \n" " s = clamp(sat+s, 0.0, 2.0);\n" " vec3 intensity = vec3(dot(rgbTex.rgb, lumCoeff));\n" " rgbTex.rgb = mix(intensity, rgbTex.rgb, s);\n" " }; \n" //Brightness with black/white pixels to imitate photoshop lightness-offset " if(l_offset >= 0.0){ \n" " rgbTex = vec4(mix(rgbTex.rgb, white, l_offset), tex.a);\n" " }\n" " else if(l_offset < 0.0){ \n" " rgbTex = vec4(mix(rgbTex.rgb, black, -l_offset), tex.a);\n" " } \n" " preMultiplyAlpha(rgbTex);\n" " gl_FragColor = rgbTex;\n" "}\n"; getOrCreateShader(SHADERID_HSL_COLOR, sProgram); } }//End namespace avg <commit_msg>Better GPUHueSatFilter.<commit_after>// //// libavg - Media Playback Engine. //// Copyright (C) 2003-2011 Ulrich von Zadow //// //// 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 //// //// Current versions can be found at www.libavg.de //// #include "GPUHueSatFilter.h" #include "ShaderRegistry.h" #include "../base/ObjectCounter.h" #include "../base/Logger.h" #define SHADERID_HSL_COLOR "HSL_COLOR" using namespace std; namespace avg { GPUHueSatFilter::GPUHueSatFilter(const IntPoint& size, PixelFormat pf, bool bStandalone) : GPUFilter(pf, B8G8R8A8, bStandalone, 2), m_LightnessOffset(0.0), m_Hue(0.0), m_Saturation(0.0) { ObjectCounter::get()->incRef(&typeid(*this)); setDimensions(size); initShader(); } GPUHueSatFilter::~GPUHueSatFilter() { ObjectCounter::get()->decRef(&typeid(*this)); } void GPUHueSatFilter::setParams(int hue, int saturation, int light_add, bool colorize) { m_Hue = float(hue); m_Saturation = saturation / 100.0f; m_LightnessOffset = light_add / 100.0f; m_bColorize = colorize; } void GPUHueSatFilter::applyOnGPU(GLTexturePtr pSrcTex) { OGLShaderPtr pShader = getShader(SHADERID_HSL_COLOR); glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); pShader->activate(); pShader->setUniformFloatParam("hue", m_Hue); pShader->setUniformFloatParam("sat", m_Saturation); pShader->setUniformFloatParam("l_offset", m_LightnessOffset); pShader->setUniformIntParam("b_colorize", (int)m_bColorize); pShader->setUniformIntParam("texture", 0); draw(pSrcTex); glproc::UseProgramObject(0); } void GPUHueSatFilter::initShader() { string sProgramHead = "const vec3 lumCoeff = vec3(0.2125, 0.7154, 0.0721);\n" "const vec3 white = vec3(1.0, 1.0, 1.0);\n" "const vec3 black = vec3(0.0, 0.0, 0.0);\n" "uniform sampler2D texture;\n" "uniform float hue;\n" "uniform float sat;\n" "uniform float l_offset;\n" "uniform bool b_colorize;\n" + getStdShaderCode() ; string sProgram = sProgramHead + "void main(void)\n" "{\n" " float tmp;\n" " float s;\n" " float l;\n" " float h;\n" " vec4 tex = texture2D(texture, gl_TexCoord[0].st);\n" " preMultiplyAlpha(tex);\n" " rgb2hsl(tex, tmp, s, l);\n" " if(b_colorize){\n" " h = hue;\n" " s = sat;\n" " }\n" " else{\n" " h = hue+tmp;\n" " }\n" " vec4 rgbTex = vec4(hsl2rgb(mod(h, 360.0), s, l), tex.a);\n" //Saturate in rgb - space to imitate photoshop filter " if(!b_colorize){ \n" " s = clamp(sat+s, 0.0, 2.0);\n" " vec3 intensity = vec3(dot(rgbTex.rgb, lumCoeff));\n" " rgbTex.rgb = mix(intensity, rgbTex.rgb, s);\n" " }; \n" //Brightness with black/white pixels to imitate photoshop lightness-offset " if(l_offset >= 0.0){ \n" " rgbTex = vec4(mix(rgbTex.rgb, white, l_offset), tex.a);\n" " }\n" " else if(l_offset < 0.0){ \n" " rgbTex = vec4(mix(rgbTex.rgb, black, -l_offset), tex.a);\n" " } \n" " preMultiplyAlpha(rgbTex);\n" " gl_FragColor = rgbTex;\n" "}\n"; getOrCreateShader(SHADERID_HSL_COLOR, sProgram); } }//End namespace avg <|endoftext|>
<commit_before> /* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkMutex.h" #include "SkOnce.h" #include "gl/GrGLInterface.h" #include "gl/GrGLAssembleInterface.h" #include "gl/command_buffer/GLTestContext_command_buffer.h" #include "../ports/SkOSLibrary.h" typedef void *EGLDisplay; typedef unsigned int EGLBoolean; typedef void *EGLConfig; typedef void *EGLSurface; typedef void *EGLContext; typedef int32_t EGLint; typedef void* EGLNativeDisplayType; typedef void* EGLNativeWindowType; typedef void (*__eglMustCastToProperFunctionPointerType)(void); #define EGL_FALSE 0 #define EGL_OPENGL_ES2_BIT 0x0004 #define EGL_CONTEXT_CLIENT_VERSION 0x3098 #define EGL_NO_SURFACE ((EGLSurface)0) #define EGL_NO_DISPLAY ((EGLDisplay)0) #define EGL_NO_CONTEXT ((EGLContext)0) #define EGL_DEFAULT_DISPLAY ((EGLNativeDisplayType)0) #define EGL_SURFACE_TYPE 0x3033 #define EGL_PBUFFER_BIT 0x0001 #define EGL_RENDERABLE_TYPE 0x3040 #define EGL_RED_SIZE 0x3024 #define EGL_GREEN_SIZE 0x3023 #define EGL_BLUE_SIZE 0x3022 #define EGL_ALPHA_SIZE 0x3021 #define EGL_DEPTH_SIZE 0x3025 #define EGL_STENCIL_SIZE 0x3025 #define EGL_SAMPLES 0x3031 #define EGL_SAMPLE_BUFFERS 0x3032 #define EGL_NONE 0x3038 #define EGL_WIDTH 0x3057 #define EGL_HEIGHT 0x3056 typedef EGLDisplay (*GetDisplayProc)(EGLNativeDisplayType display_id); typedef EGLBoolean (*InitializeProc)(EGLDisplay dpy, EGLint *major, EGLint *minor); typedef EGLBoolean (*TerminateProc)(EGLDisplay dpy); typedef EGLBoolean (*ChooseConfigProc)(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size, EGLint* num_config); typedef EGLBoolean (*GetConfigAttrib)(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint* value); typedef EGLSurface (*CreateWindowSurfaceProc)(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint* attrib_list); typedef EGLSurface (*CreatePbufferSurfaceProc)(EGLDisplay dpy, EGLConfig config, const EGLint* attrib_list); typedef EGLBoolean (*DestroySurfaceProc)(EGLDisplay dpy, EGLSurface surface); typedef EGLContext (*CreateContextProc)(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint* attrib_list); typedef EGLBoolean (*DestroyContextProc)(EGLDisplay dpy, EGLContext ctx); typedef EGLBoolean (*MakeCurrentProc)(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); typedef EGLBoolean (*SwapBuffersProc)(EGLDisplay dpy, EGLSurface surface); typedef __eglMustCastToProperFunctionPointerType (*GetProcAddressProc)(const char* procname); static GetDisplayProc gfGetDisplay = nullptr; static InitializeProc gfInitialize = nullptr; static TerminateProc gfTerminate = nullptr; static ChooseConfigProc gfChooseConfig = nullptr; static GetConfigAttrib gfGetConfigAttrib = nullptr; static CreateWindowSurfaceProc gfCreateWindowSurface = nullptr; static CreatePbufferSurfaceProc gfCreatePbufferSurface = nullptr; static DestroySurfaceProc gfDestroySurface = nullptr; static CreateContextProc gfCreateContext = nullptr; static DestroyContextProc gfDestroyContext = nullptr; static MakeCurrentProc gfMakeCurrent = nullptr; static SwapBuffersProc gfSwapBuffers = nullptr; static GetProcAddressProc gfGetProcAddress = nullptr; static void* gLibrary = nullptr; static bool gfFunctionsLoadedSuccessfully = false; namespace { static void load_command_buffer_functions() { if (!gLibrary) { static constexpr const char* libName = #if defined _WIN32 "command_buffer_gles2.dll"; #elif defined SK_BUILD_FOR_MAC "libcommand_buffer_gles2.dylib"; #else "libcommand_buffer_gles2.so"; #endif // defined _WIN32 gLibrary = DynamicLoadLibrary(libName); if (gLibrary) { gfGetDisplay = (GetDisplayProc)GetProcedureAddress(gLibrary, "eglGetDisplay"); gfInitialize = (InitializeProc)GetProcedureAddress(gLibrary, "eglInitialize"); gfTerminate = (TerminateProc)GetProcedureAddress(gLibrary, "eglTerminate"); gfChooseConfig = (ChooseConfigProc)GetProcedureAddress(gLibrary, "eglChooseConfig"); gfGetConfigAttrib = (GetConfigAttrib)GetProcedureAddress(gLibrary, "eglGetConfigAttrib"); gfCreateWindowSurface = (CreateWindowSurfaceProc)GetProcedureAddress(gLibrary, "eglCreateWindowSurface"); gfCreatePbufferSurface = (CreatePbufferSurfaceProc)GetProcedureAddress(gLibrary, "eglCreatePbufferSurface"); gfDestroySurface = (DestroySurfaceProc)GetProcedureAddress(gLibrary, "eglDestroySurface"); gfCreateContext = (CreateContextProc)GetProcedureAddress(gLibrary, "eglCreateContext"); gfDestroyContext = (DestroyContextProc)GetProcedureAddress(gLibrary, "eglDestroyContext"); gfMakeCurrent = (MakeCurrentProc)GetProcedureAddress(gLibrary, "eglMakeCurrent"); gfSwapBuffers = (SwapBuffersProc)GetProcedureAddress(gLibrary, "eglSwapBuffers"); gfGetProcAddress = (GetProcAddressProc)GetProcedureAddress(gLibrary, "eglGetProcAddress"); gfFunctionsLoadedSuccessfully = gfGetDisplay && gfInitialize && gfTerminate && gfChooseConfig && gfCreateWindowSurface && gfCreatePbufferSurface && gfDestroySurface && gfCreateContext && gfDestroyContext && gfMakeCurrent && gfSwapBuffers && gfGetProcAddress; } else { SkDebugf("Could not load %s.\n", libName); } } } static GrGLFuncPtr command_buffer_get_gl_proc(void* ctx, const char name[]) { if (!gfFunctionsLoadedSuccessfully) { return nullptr; } return gfGetProcAddress(name); } static void load_command_buffer_once() { static SkOnce once; once(load_command_buffer_functions); } static const GrGLInterface* create_command_buffer_interface() { load_command_buffer_once(); if (!gfFunctionsLoadedSuccessfully) { return nullptr; } return GrGLAssembleGLESInterface(gLibrary, command_buffer_get_gl_proc); } } // anonymous namespace namespace sk_gpu_test { CommandBufferGLTestContext::CommandBufferGLTestContext() : fContext(EGL_NO_CONTEXT), fDisplay(EGL_NO_DISPLAY), fSurface(EGL_NO_SURFACE) { static const EGLint configAttribs[] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; static const EGLint surfaceAttribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE }; initializeGLContext(nullptr, configAttribs, surfaceAttribs); } CommandBufferGLTestContext::CommandBufferGLTestContext(void *nativeWindow, int msaaSampleCount) { static const EGLint surfaceAttribs[] = {EGL_NONE}; EGLint configAttribs[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_STENCIL_SIZE, 8, EGL_SAMPLE_BUFFERS, 1, EGL_SAMPLES, msaaSampleCount, EGL_NONE }; if (msaaSampleCount == 0) { configAttribs[12] = EGL_NONE; } initializeGLContext(nativeWindow, configAttribs, surfaceAttribs); } void CommandBufferGLTestContext::initializeGLContext(void *nativeWindow, const int *configAttribs, const int *surfaceAttribs) { load_command_buffer_once(); if (!gfFunctionsLoadedSuccessfully) { SkDebugf("Command Buffer: Could not load EGL functions.\n"); return; } fDisplay = gfGetDisplay(EGL_DEFAULT_DISPLAY); if (EGL_NO_DISPLAY == fDisplay) { SkDebugf("Command Buffer: Could not create EGL display.\n"); return; } if (!gfInitialize(fDisplay, nullptr, nullptr)) { SkDebugf("Command Buffer: Could not initialize EGL display.\n"); this->destroyGLContext(); return; } EGLint numConfigs; if (!gfChooseConfig(fDisplay, configAttribs, static_cast<EGLConfig *>(&fConfig), 1, &numConfigs) || numConfigs != 1) { SkDebugf("Command Buffer: Could not choose EGL config.\n"); this->destroyGLContext(); return; } if (nativeWindow) { fSurface = gfCreateWindowSurface(fDisplay, static_cast<EGLConfig>(fConfig), (EGLNativeWindowType) nativeWindow, surfaceAttribs); } else { fSurface = gfCreatePbufferSurface(fDisplay, static_cast<EGLConfig>(fConfig), surfaceAttribs); } if (EGL_NO_SURFACE == fSurface) { SkDebugf("Command Buffer: Could not create EGL surface.\n"); this->destroyGLContext(); return; } static const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; fContext = gfCreateContext(fDisplay, static_cast<EGLConfig>(fConfig), nullptr, contextAttribs); if (EGL_NO_CONTEXT == fContext) { SkDebugf("Command Buffer: Could not create EGL context.\n"); this->destroyGLContext(); return; } if (!gfMakeCurrent(fDisplay, fSurface, fSurface, fContext)) { SkDebugf("Command Buffer: Could not make EGL context current.\n"); this->destroyGLContext(); return; } SkAutoTUnref<const GrGLInterface> gl(create_command_buffer_interface()); if (nullptr == gl.get()) { SkDebugf("Command Buffer: Could not create CommandBuffer GL interface.\n"); this->destroyGLContext(); return; } if (!gl->validate()) { SkDebugf("Command Buffer: Could not validate CommandBuffer GL interface.\n"); this->destroyGLContext(); return; } this->init(gl.release()); } CommandBufferGLTestContext::~CommandBufferGLTestContext() { this->teardown(); this->destroyGLContext(); } void CommandBufferGLTestContext::destroyGLContext() { if (!gfFunctionsLoadedSuccessfully) { return; } if (EGL_NO_DISPLAY == fDisplay) { return; } if (EGL_NO_CONTEXT != fContext) { gfDestroyContext(fDisplay, fContext); fContext = EGL_NO_CONTEXT; } // Call MakeCurrent after destroying the context, so that the EGL implementation knows that // the context is not used anymore after it is released from being current. This way // command buffer does not need to abandon the context before destruction, and no // client-side errors are printed. gfMakeCurrent(fDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (EGL_NO_SURFACE != fSurface) { gfDestroySurface(fDisplay, fSurface); fSurface = EGL_NO_SURFACE; } fDisplay = EGL_NO_DISPLAY; } void CommandBufferGLTestContext::onPlatformMakeCurrent() const { if (!gfFunctionsLoadedSuccessfully) { return; } if (!gfMakeCurrent(fDisplay, fSurface, fSurface, fContext)) { SkDebugf("Command Buffer: Could not make EGL context current.\n"); } } void CommandBufferGLTestContext::onPlatformSwapBuffers() const { if (!gfFunctionsLoadedSuccessfully) { return; } if (!gfSwapBuffers(fDisplay, fSurface)) { SkDebugf("Command Buffer: Could not complete gfSwapBuffers.\n"); } } GrGLFuncPtr CommandBufferGLTestContext::onPlatformGetProcAddress(const char *name) const { if (!gfFunctionsLoadedSuccessfully) { return nullptr; } return gfGetProcAddress(name); } void CommandBufferGLTestContext::presentCommandBuffer() { if (this->gl()) { this->gl()->fFunctions.fFlush(); } this->onPlatformSwapBuffers(); } bool CommandBufferGLTestContext::makeCurrent() { return gfMakeCurrent(fDisplay, fSurface, fSurface, fContext) != EGL_FALSE; } int CommandBufferGLTestContext::getStencilBits() { EGLint result = 0; gfGetConfigAttrib(fDisplay, static_cast<EGLConfig>(fConfig), EGL_STENCIL_SIZE, &result); return result; } int CommandBufferGLTestContext::getSampleCount() { EGLint result = 0; gfGetConfigAttrib(fDisplay, static_cast<EGLConfig>(fConfig), EGL_SAMPLES, &result); return result; } } // namespace sk_gpu_test <commit_msg>Use SkOnce to squelch command buffer spam<commit_after> /* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkMutex.h" #include "SkOnce.h" #include "gl/GrGLInterface.h" #include "gl/GrGLAssembleInterface.h" #include "gl/command_buffer/GLTestContext_command_buffer.h" #include "../ports/SkOSLibrary.h" typedef void *EGLDisplay; typedef unsigned int EGLBoolean; typedef void *EGLConfig; typedef void *EGLSurface; typedef void *EGLContext; typedef int32_t EGLint; typedef void* EGLNativeDisplayType; typedef void* EGLNativeWindowType; typedef void (*__eglMustCastToProperFunctionPointerType)(void); #define EGL_FALSE 0 #define EGL_OPENGL_ES2_BIT 0x0004 #define EGL_CONTEXT_CLIENT_VERSION 0x3098 #define EGL_NO_SURFACE ((EGLSurface)0) #define EGL_NO_DISPLAY ((EGLDisplay)0) #define EGL_NO_CONTEXT ((EGLContext)0) #define EGL_DEFAULT_DISPLAY ((EGLNativeDisplayType)0) #define EGL_SURFACE_TYPE 0x3033 #define EGL_PBUFFER_BIT 0x0001 #define EGL_RENDERABLE_TYPE 0x3040 #define EGL_RED_SIZE 0x3024 #define EGL_GREEN_SIZE 0x3023 #define EGL_BLUE_SIZE 0x3022 #define EGL_ALPHA_SIZE 0x3021 #define EGL_DEPTH_SIZE 0x3025 #define EGL_STENCIL_SIZE 0x3025 #define EGL_SAMPLES 0x3031 #define EGL_SAMPLE_BUFFERS 0x3032 #define EGL_NONE 0x3038 #define EGL_WIDTH 0x3057 #define EGL_HEIGHT 0x3056 typedef EGLDisplay (*GetDisplayProc)(EGLNativeDisplayType display_id); typedef EGLBoolean (*InitializeProc)(EGLDisplay dpy, EGLint *major, EGLint *minor); typedef EGLBoolean (*TerminateProc)(EGLDisplay dpy); typedef EGLBoolean (*ChooseConfigProc)(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size, EGLint* num_config); typedef EGLBoolean (*GetConfigAttrib)(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint* value); typedef EGLSurface (*CreateWindowSurfaceProc)(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint* attrib_list); typedef EGLSurface (*CreatePbufferSurfaceProc)(EGLDisplay dpy, EGLConfig config, const EGLint* attrib_list); typedef EGLBoolean (*DestroySurfaceProc)(EGLDisplay dpy, EGLSurface surface); typedef EGLContext (*CreateContextProc)(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint* attrib_list); typedef EGLBoolean (*DestroyContextProc)(EGLDisplay dpy, EGLContext ctx); typedef EGLBoolean (*MakeCurrentProc)(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); typedef EGLBoolean (*SwapBuffersProc)(EGLDisplay dpy, EGLSurface surface); typedef __eglMustCastToProperFunctionPointerType (*GetProcAddressProc)(const char* procname); static GetDisplayProc gfGetDisplay = nullptr; static InitializeProc gfInitialize = nullptr; static TerminateProc gfTerminate = nullptr; static ChooseConfigProc gfChooseConfig = nullptr; static GetConfigAttrib gfGetConfigAttrib = nullptr; static CreateWindowSurfaceProc gfCreateWindowSurface = nullptr; static CreatePbufferSurfaceProc gfCreatePbufferSurface = nullptr; static DestroySurfaceProc gfDestroySurface = nullptr; static CreateContextProc gfCreateContext = nullptr; static DestroyContextProc gfDestroyContext = nullptr; static MakeCurrentProc gfMakeCurrent = nullptr; static SwapBuffersProc gfSwapBuffers = nullptr; static GetProcAddressProc gfGetProcAddress = nullptr; static void* gLibrary = nullptr; static bool gfFunctionsLoadedSuccessfully = false; namespace { static void load_command_buffer_functions() { if (!gLibrary) { static constexpr const char* libName = #if defined _WIN32 "command_buffer_gles2.dll"; #elif defined SK_BUILD_FOR_MAC "libcommand_buffer_gles2.dylib"; #else "libcommand_buffer_gles2.so"; #endif // defined _WIN32 gLibrary = DynamicLoadLibrary(libName); if (gLibrary) { gfGetDisplay = (GetDisplayProc)GetProcedureAddress(gLibrary, "eglGetDisplay"); gfInitialize = (InitializeProc)GetProcedureAddress(gLibrary, "eglInitialize"); gfTerminate = (TerminateProc)GetProcedureAddress(gLibrary, "eglTerminate"); gfChooseConfig = (ChooseConfigProc)GetProcedureAddress(gLibrary, "eglChooseConfig"); gfGetConfigAttrib = (GetConfigAttrib)GetProcedureAddress(gLibrary, "eglGetConfigAttrib"); gfCreateWindowSurface = (CreateWindowSurfaceProc)GetProcedureAddress(gLibrary, "eglCreateWindowSurface"); gfCreatePbufferSurface = (CreatePbufferSurfaceProc)GetProcedureAddress(gLibrary, "eglCreatePbufferSurface"); gfDestroySurface = (DestroySurfaceProc)GetProcedureAddress(gLibrary, "eglDestroySurface"); gfCreateContext = (CreateContextProc)GetProcedureAddress(gLibrary, "eglCreateContext"); gfDestroyContext = (DestroyContextProc)GetProcedureAddress(gLibrary, "eglDestroyContext"); gfMakeCurrent = (MakeCurrentProc)GetProcedureAddress(gLibrary, "eglMakeCurrent"); gfSwapBuffers = (SwapBuffersProc)GetProcedureAddress(gLibrary, "eglSwapBuffers"); gfGetProcAddress = (GetProcAddressProc)GetProcedureAddress(gLibrary, "eglGetProcAddress"); gfFunctionsLoadedSuccessfully = gfGetDisplay && gfInitialize && gfTerminate && gfChooseConfig && gfCreateWindowSurface && gfCreatePbufferSurface && gfDestroySurface && gfCreateContext && gfDestroyContext && gfMakeCurrent && gfSwapBuffers && gfGetProcAddress; } else { SkDebugf("Could not load %s.\n", libName); } } } static GrGLFuncPtr command_buffer_get_gl_proc(void* ctx, const char name[]) { if (!gfFunctionsLoadedSuccessfully) { return nullptr; } return gfGetProcAddress(name); } static void load_command_buffer_once() { static SkOnce once; once(load_command_buffer_functions); } static const GrGLInterface* create_command_buffer_interface() { load_command_buffer_once(); if (!gfFunctionsLoadedSuccessfully) { return nullptr; } return GrGLAssembleGLESInterface(gLibrary, command_buffer_get_gl_proc); } } // anonymous namespace namespace sk_gpu_test { CommandBufferGLTestContext::CommandBufferGLTestContext() : fContext(EGL_NO_CONTEXT), fDisplay(EGL_NO_DISPLAY), fSurface(EGL_NO_SURFACE) { static const EGLint configAttribs[] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; static const EGLint surfaceAttribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE }; initializeGLContext(nullptr, configAttribs, surfaceAttribs); } CommandBufferGLTestContext::CommandBufferGLTestContext(void *nativeWindow, int msaaSampleCount) { static const EGLint surfaceAttribs[] = {EGL_NONE}; EGLint configAttribs[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_STENCIL_SIZE, 8, EGL_SAMPLE_BUFFERS, 1, EGL_SAMPLES, msaaSampleCount, EGL_NONE }; if (msaaSampleCount == 0) { configAttribs[12] = EGL_NONE; } initializeGLContext(nativeWindow, configAttribs, surfaceAttribs); } void CommandBufferGLTestContext::initializeGLContext(void *nativeWindow, const int *configAttribs, const int *surfaceAttribs) { load_command_buffer_once(); if (!gfFunctionsLoadedSuccessfully) { static SkOnce once; once([] { SkDebugf("Command Buffer: Could not load EGL functions.\n"); }); return; } fDisplay = gfGetDisplay(EGL_DEFAULT_DISPLAY); if (EGL_NO_DISPLAY == fDisplay) { SkDebugf("Command Buffer: Could not create EGL display.\n"); return; } if (!gfInitialize(fDisplay, nullptr, nullptr)) { SkDebugf("Command Buffer: Could not initialize EGL display.\n"); this->destroyGLContext(); return; } EGLint numConfigs; if (!gfChooseConfig(fDisplay, configAttribs, static_cast<EGLConfig *>(&fConfig), 1, &numConfigs) || numConfigs != 1) { SkDebugf("Command Buffer: Could not choose EGL config.\n"); this->destroyGLContext(); return; } if (nativeWindow) { fSurface = gfCreateWindowSurface(fDisplay, static_cast<EGLConfig>(fConfig), (EGLNativeWindowType) nativeWindow, surfaceAttribs); } else { fSurface = gfCreatePbufferSurface(fDisplay, static_cast<EGLConfig>(fConfig), surfaceAttribs); } if (EGL_NO_SURFACE == fSurface) { SkDebugf("Command Buffer: Could not create EGL surface.\n"); this->destroyGLContext(); return; } static const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; fContext = gfCreateContext(fDisplay, static_cast<EGLConfig>(fConfig), nullptr, contextAttribs); if (EGL_NO_CONTEXT == fContext) { SkDebugf("Command Buffer: Could not create EGL context.\n"); this->destroyGLContext(); return; } if (!gfMakeCurrent(fDisplay, fSurface, fSurface, fContext)) { SkDebugf("Command Buffer: Could not make EGL context current.\n"); this->destroyGLContext(); return; } SkAutoTUnref<const GrGLInterface> gl(create_command_buffer_interface()); if (nullptr == gl.get()) { SkDebugf("Command Buffer: Could not create CommandBuffer GL interface.\n"); this->destroyGLContext(); return; } if (!gl->validate()) { SkDebugf("Command Buffer: Could not validate CommandBuffer GL interface.\n"); this->destroyGLContext(); return; } this->init(gl.release()); } CommandBufferGLTestContext::~CommandBufferGLTestContext() { this->teardown(); this->destroyGLContext(); } void CommandBufferGLTestContext::destroyGLContext() { if (!gfFunctionsLoadedSuccessfully) { return; } if (EGL_NO_DISPLAY == fDisplay) { return; } if (EGL_NO_CONTEXT != fContext) { gfDestroyContext(fDisplay, fContext); fContext = EGL_NO_CONTEXT; } // Call MakeCurrent after destroying the context, so that the EGL implementation knows that // the context is not used anymore after it is released from being current. This way // command buffer does not need to abandon the context before destruction, and no // client-side errors are printed. gfMakeCurrent(fDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (EGL_NO_SURFACE != fSurface) { gfDestroySurface(fDisplay, fSurface); fSurface = EGL_NO_SURFACE; } fDisplay = EGL_NO_DISPLAY; } void CommandBufferGLTestContext::onPlatformMakeCurrent() const { if (!gfFunctionsLoadedSuccessfully) { return; } if (!gfMakeCurrent(fDisplay, fSurface, fSurface, fContext)) { SkDebugf("Command Buffer: Could not make EGL context current.\n"); } } void CommandBufferGLTestContext::onPlatformSwapBuffers() const { if (!gfFunctionsLoadedSuccessfully) { return; } if (!gfSwapBuffers(fDisplay, fSurface)) { SkDebugf("Command Buffer: Could not complete gfSwapBuffers.\n"); } } GrGLFuncPtr CommandBufferGLTestContext::onPlatformGetProcAddress(const char *name) const { if (!gfFunctionsLoadedSuccessfully) { return nullptr; } return gfGetProcAddress(name); } void CommandBufferGLTestContext::presentCommandBuffer() { if (this->gl()) { this->gl()->fFunctions.fFlush(); } this->onPlatformSwapBuffers(); } bool CommandBufferGLTestContext::makeCurrent() { return gfMakeCurrent(fDisplay, fSurface, fSurface, fContext) != EGL_FALSE; } int CommandBufferGLTestContext::getStencilBits() { EGLint result = 0; gfGetConfigAttrib(fDisplay, static_cast<EGLConfig>(fConfig), EGL_STENCIL_SIZE, &result); return result; } int CommandBufferGLTestContext::getSampleCount() { EGLint result = 0; gfGetConfigAttrib(fDisplay, static_cast<EGLConfig>(fConfig), EGL_SAMPLES, &result); return result; } } // namespace sk_gpu_test <|endoftext|>
<commit_before>// Sh: A GPU metaprogramming language. // // Copyright 2003-2005 Serious Hack Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA ////////////////////////////////////////////////////////////////////////////// #include <map> #include <string> #include <sstream> #include <algorithm> #include "ShAlgebra.hpp" #include "ShCtrlGraph.hpp" #include "ShDebug.hpp" #include "ShError.hpp" #include "ShOptimizations.hpp" #include "ShInternals.hpp" #include "ShContext.hpp" #include "ShManipulator.hpp" #include "ShFixedManipulator.hpp" namespace SH { ShProgram connect(ShProgram pa, ShProgram pb) { ShProgramNodePtr a = pa.node(); ShProgramNodePtr b = pb.node(); if( !a || !b ) SH_DEBUG_WARN( "Connecting with a null ShProgram" ); if( !a ) return b; if( !b ) return a; int aosize = a->outputs.size(); int bisize = b->inputs.size(); std::string rtarget; if (a->target().empty()) { rtarget = b->target(); // A doesn't have a target. Use b's. } else { if (b->target().empty() || a->target() == b->target()) { rtarget = a->target(); // A has a target, b doesn't } else { SH_DEBUG_WARN("Connecting two different targets. Using empty target for result."); rtarget = ""; // Connecting different targets. } } ShProgramNodePtr program = new ShProgramNode(rtarget); ShCtrlGraphNodePtr heada, taila, headb, tailb; a->ctrlGraph->copy(heada, taila); b->ctrlGraph->copy(headb, tailb); taila->append(headb); ShCtrlGraphPtr new_graph = new ShCtrlGraph(heada, tailb); program->ctrlGraph = new_graph; program->inputs = a->inputs; // push back extra inputs from b if aosize < bisize if(aosize < bisize) { ShProgramNode::VarList::const_iterator II = b->inputs.begin(); for(int i = 0; i < aosize; ++i, ++II); for(; II != b->inputs.end(); ++II) { program->inputs.push_back(*II); } } program->outputs = b->outputs; // push back extra outputs from a if aosize > bisize if(aosize > bisize) { ShProgramNode::VarList::const_iterator II = a->outputs.begin(); for(int i = 0; i < bisize; ++i, ++II); for(; II != a->outputs.end(); ++II) { program->outputs.push_back(*II); } } ShVarMap varMap; ShContext::current()->enter(program); ShProgramNode::VarList::const_iterator I, J; ShProgramNode::VarList InOutInputs; ShProgramNode::VarList InOutOutputs; // replace outputs and inputs connected together by temps for (I = a->outputs.begin(), J = b->inputs.begin(); I != a->outputs.end() && J != b->inputs.end(); ++I, ++J) { if((*I)->size() != (*J)->size()) { std::ostringstream err; err << "Cannot smash variables " << (*I)->nameOfType() << " " << (*I)->name() << " and " << (*J)->nameOfType() << " " << (*J)->name() << " with different sizes" << std::endl; err << "while connecting outputs: "; ShProgramNode::print(err, a->outputs) << std::endl; err << "to inputs: "; ShProgramNode::print(err, b->inputs) << std::endl; ShContext::current()->exit(); shError(ShAlgebraException(err.str())); return ShProgram(ShProgramNodePtr(0)); } ShVariableNodePtr n = (*I)->clone(SH_TEMP); varMap[*I] = n; varMap[*J] = n; if((*I)->kind() == SH_INOUT) InOutInputs.push_back((*I)); if((*J)->kind() == SH_INOUT) InOutOutputs.push_back((*J)); } // Change connected InOut variables to either Input or Output only // (since they have been connected and turned into temps internally) ShCtrlGraphNodePtr graphEntry; for (I = InOutInputs.begin(); I != InOutInputs.end(); ++I) { if(!graphEntry) graphEntry = program->ctrlGraph->prependEntry(); ShVariableNodePtr newInput((*I)->clone(SH_INPUT)); std::replace(program->inputs.begin(), program->inputs.end(), (*I), newInput); program->inputs.pop_back(); graphEntry->block->addStatement(ShStatement( ShVariable(varMap[*I]), SH_OP_ASN, ShVariable(newInput))); } ShCtrlGraphNodePtr graphExit; for (I = InOutOutputs.begin(); I != InOutOutputs.end(); ++I) { if(!graphExit) graphExit = program->ctrlGraph->appendExit(); ShVariableNodePtr newOutput((*I)->clone(SH_OUTPUT)); std::replace(program->outputs.begin(), program->outputs.end(), (*I), newOutput); program->outputs.pop_back(); graphExit->block->addStatement(ShStatement( ShVariable(newOutput), SH_OP_ASN, ShVariable(varMap[*I]))); } ShContext::current()->exit(); ShVariableReplacer replacer(varMap); program->ctrlGraph->dfs(replacer); program->collectVariables(); optimize(program); return program; } ShProgram combine(ShProgram pa, ShProgram pb) { ShProgramNodePtr a = pa.node(); ShProgramNodePtr b = pb.node(); std::string rtarget; if( !a || !b ) SH_DEBUG_WARN( "Connecting with a null ShProgram" ); if (!a) return b; if (!b) return a; if (a->target().empty()) { rtarget = b->target(); // A doesn't have a target. Use b's. } else { if (b->target().empty() || a->target() == b->target()) { rtarget = a->target(); // A has a target, b doesn't } else { rtarget = ""; // Connecting different targets. } } ShProgramNodePtr program = new ShProgramNode(rtarget); ShCtrlGraphNodePtr heada, taila, headb, tailb; a->ctrlGraph->copy(heada, taila); b->ctrlGraph->copy(headb, tailb); taila->append(headb); ShCtrlGraphPtr new_graph = new ShCtrlGraph(heada, tailb); program->ctrlGraph = new_graph; program->inputs = a->inputs; program->inputs.insert(program->inputs.end(), b->inputs.begin(), b->inputs.end()); program->outputs = a->outputs; program->outputs.insert(program->outputs.end(), b->outputs.begin(), b->outputs.end()); program->collectVariables(); optimize(program); return program; } // Duplicates to inputs with matching name/type ShProgram mergeNames(ShProgram p) { typedef std::pair<std::string, int> InputType; typedef std::map< InputType, int > FirstOccurenceMap; // position of first occurence of an input type typedef std::vector< std::vector<int> > Duplicates; FirstOccurenceMap firsts; // dups[i] stores the set of positions that have matching input types with position i. // The whole set is stored in the smallest i position. Duplicates dups( p.node()->inputs.size(), std::vector<int>()); std::size_t i = 0; for(ShProgramNode::VarList::const_iterator I = p.node()->inputs.begin(); I != p.node()->inputs.end(); ++I, ++i) { InputType it( (*I)->name(), (*I)->size() ); if( firsts.find( it ) != firsts.end() ) { // duplicate dups[ firsts[it] ].push_back(i); } else { firsts[it] = i; dups[i].push_back(i); } } std::vector<int> swizzle; ShFixedManipulator duplicator; for(i = 0; i < dups.size(); ++i) { if( dups[i].empty() ) continue; for(std::size_t j = 0; j < dups[i].size(); ++j) swizzle.push_back(dups[i][j]); if( duplicator ) duplicator = duplicator & shDup(dups[i].size()); else duplicator = shDup(dups[i].size()); } ShProgram result = p << shSwizzle(swizzle); if( duplicator ) result = result << duplicator; return result.node(); } ShProgram namedCombine(ShProgram a, ShProgram b) { return mergeNames(combine(a, b)); } ShProgram namedConnect(ShProgram pa, ShProgram pb, bool keepExtra) { ShProgramNodeCPtr a = pa.node(); ShProgramNodeCPtr b = pb.node(); // positions of a pair of matched a output and b input typedef std::map<int, int> MatchedChannelMap; std::vector<bool> aMatch(a->outputs.size(), false); std::vector<bool> bMatch(b->inputs.size(), false); MatchedChannelMap mcm; std::size_t i, j; ShProgramNode::VarList::const_iterator I, J; i = 0; for(I = a->outputs.begin(); I != a->outputs.end(); ++I, ++i) { j = 0; for(J = b->inputs.begin(); J != b->inputs.end(); ++J, ++j) { if(bMatch[j]) continue; if((*I)->name() != (*J)->name()) continue; if((*I)->size() != (*J)->size()) { SH_DEBUG_WARN("Named connect matched channel name " << (*I)->name() << " but output size " << (*I)->size() << " != " << " input size " << (*J)->size() ); continue; } mcm[i] = j; aMatch[i] = true; bMatch[j] = true; } } std::vector<int> swiz(b->inputs.size(), 0); for(MatchedChannelMap::iterator mcmit = mcm.begin(); mcmit != mcm.end(); ++mcmit) { swiz[mcmit->second] = mcmit->first; } // swizzle unmatched inputs and make a pass them through properly ShProgram passer = SH_BEGIN_PROGRAM() {} SH_END; int newInputIdx = a->outputs.size(); // index of next new input added to a for(j = 0, J= b->inputs.begin(); J != b->inputs.end(); ++J, ++j) { if( !bMatch[j] ) { ShProgram passOne = SH_BEGIN_PROGRAM() { ShVariable var((*J)->clone(SH_INOUT)); } SH_END; passer = passer & passOne; swiz[j] = newInputIdx++; } } ShProgram aPass = combine(pa, passer); if( keepExtra ) { for(i = 0; i < aMatch.size(); ++i) { if( !aMatch[i] ) swiz.push_back(i); } } return mergeNames(pb << ( shSwizzle(swiz) << aPass )); } ShProgram renameInput(ShProgram a, const std::string& oldName, const std::string& newName) { ShProgram renamer = SH_BEGIN_PROGRAM() { for(ShProgramNode::VarList::const_iterator I = a.node()->inputs.begin(); I != a.node()->inputs.end(); ++I) { ShVariable var((*I)->clone(SH_INOUT)); if (!(*I)->has_name()) continue; std::string name = (*I)->name(); if( name == oldName ) { var.name(newName); } else { var.name(name); } } } SH_END; return connect(renamer, a); } // TODO factor out common code from renameInput, renameOutput ShProgram renameOutput(ShProgram a, const std::string& oldName, const std::string& newName) { ShProgram renamer = SH_BEGIN_PROGRAM() { for(ShProgramNode::VarList::const_iterator I = a.node()->outputs.begin(); I != a.node()->outputs.end(); ++I) { ShVariable var((*I)->clone(SH_INOUT)); if (!(*I)->has_name()) continue; std::string name = (*I)->name(); if( name == oldName ) { var.name(newName); } else { var.name(name); } } } SH_END; return connect(a, renamer); } ShProgram namedAlign(ShProgram a, ShProgram b) { ShManipulator<std::string> ordering; for(ShProgramNode::VarList::const_iterator I = b.node()->inputs.begin(); I != b.node()->inputs.end(); ++I) { ordering((*I)->name()); } return ordering << a; } ShProgram operator<<(ShProgram a, ShProgram b) { return connect(b,a); } ShProgram operator>>(ShProgram a, ShProgram b) { return connect(a,b); } ShProgram operator&(ShProgram a, ShProgram b) { return combine(a, b); } ShProgram operator>>(ShProgram p, const ShVariable &var) { return replaceVariable(p, var); } ShProgram replaceVariable(ShProgram a, const ShVariable& v) { ShProgram program(a.node()->clone()); ShVarMap varMap; ShContext::current()->enter(program.node()); // make a new input ShVariableNodePtr newInput(v.node()->clone(SH_INPUT)); varMap[v.node()] = newInput; ShContext::current()->exit(); ShVariableReplacer replacer(varMap); program.node()->ctrlGraph->dfs(replacer); optimize(program); return program; } ShProgram operator<<(ShProgram a, const ShVariable& var) { ShProgram vNibble = SH_BEGIN_PROGRAM() { ShVariable out(var.node()->clone(SH_OUTPUT, var.size(), var.valueType(), SH_SEMANTICTYPE_END, true, false)); shASN(out, var); } SH_END_PROGRAM; return connect(vNibble, a); } } <commit_msg>Fix indentation<commit_after>// Sh: A GPU metaprogramming language. // // Copyright 2003-2005 Serious Hack Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA ////////////////////////////////////////////////////////////////////////////// #include <map> #include <string> #include <sstream> #include <algorithm> #include "ShAlgebra.hpp" #include "ShCtrlGraph.hpp" #include "ShDebug.hpp" #include "ShError.hpp" #include "ShOptimizations.hpp" #include "ShInternals.hpp" #include "ShContext.hpp" #include "ShManipulator.hpp" #include "ShFixedManipulator.hpp" namespace SH { ShProgram connect(ShProgram pa, ShProgram pb) { ShProgramNodePtr a = pa.node(); ShProgramNodePtr b = pb.node(); if( !a || !b ) SH_DEBUG_WARN( "Connecting with a null ShProgram" ); if( !a ) return b; if( !b ) return a; int aosize = a->outputs.size(); int bisize = b->inputs.size(); std::string rtarget; if (a->target().empty()) { rtarget = b->target(); // A doesn't have a target. Use b's. } else { if (b->target().empty() || a->target() == b->target()) { rtarget = a->target(); // A has a target, b doesn't } else { SH_DEBUG_WARN("Connecting two different targets. Using empty target for result."); rtarget = ""; // Connecting different targets. } } ShProgramNodePtr program = new ShProgramNode(rtarget); ShCtrlGraphNodePtr heada, taila, headb, tailb; a->ctrlGraph->copy(heada, taila); b->ctrlGraph->copy(headb, tailb); taila->append(headb); ShCtrlGraphPtr new_graph = new ShCtrlGraph(heada, tailb); program->ctrlGraph = new_graph; program->inputs = a->inputs; // push back extra inputs from b if aosize < bisize if(aosize < bisize) { ShProgramNode::VarList::const_iterator II = b->inputs.begin(); for(int i = 0; i < aosize; ++i, ++II); for(; II != b->inputs.end(); ++II) { program->inputs.push_back(*II); } } program->outputs = b->outputs; // push back extra outputs from a if aosize > bisize if(aosize > bisize) { ShProgramNode::VarList::const_iterator II = a->outputs.begin(); for(int i = 0; i < bisize; ++i, ++II); for(; II != a->outputs.end(); ++II) { program->outputs.push_back(*II); } } ShVarMap varMap; ShContext::current()->enter(program); ShProgramNode::VarList::const_iterator I, J; ShProgramNode::VarList InOutInputs; ShProgramNode::VarList InOutOutputs; // replace outputs and inputs connected together by temps for (I = a->outputs.begin(), J = b->inputs.begin(); I != a->outputs.end() && J != b->inputs.end(); ++I, ++J) { if((*I)->size() != (*J)->size()) { std::ostringstream err; err << "Cannot smash variables " << (*I)->nameOfType() << " " << (*I)->name() << " and " << (*J)->nameOfType() << " " << (*J)->name() << " with different sizes" << std::endl; err << "while connecting outputs: "; ShProgramNode::print(err, a->outputs) << std::endl; err << "to inputs: "; ShProgramNode::print(err, b->inputs) << std::endl; ShContext::current()->exit(); shError(ShAlgebraException(err.str())); return ShProgram(ShProgramNodePtr(0)); } ShVariableNodePtr n = (*I)->clone(SH_TEMP); varMap[*I] = n; varMap[*J] = n; if((*I)->kind() == SH_INOUT) InOutInputs.push_back((*I)); if((*J)->kind() == SH_INOUT) InOutOutputs.push_back((*J)); } // Change connected InOut variables to either Input or Output only // (since they have been connected and turned into temps internally) ShCtrlGraphNodePtr graphEntry; for (I = InOutInputs.begin(); I != InOutInputs.end(); ++I) { if(!graphEntry) graphEntry = program->ctrlGraph->prependEntry(); ShVariableNodePtr newInput((*I)->clone(SH_INPUT)); std::replace(program->inputs.begin(), program->inputs.end(), (*I), newInput); program->inputs.pop_back(); graphEntry->block->addStatement(ShStatement( ShVariable(varMap[*I]), SH_OP_ASN, ShVariable(newInput))); } ShCtrlGraphNodePtr graphExit; for (I = InOutOutputs.begin(); I != InOutOutputs.end(); ++I) { if(!graphExit) graphExit = program->ctrlGraph->appendExit(); ShVariableNodePtr newOutput((*I)->clone(SH_OUTPUT)); std::replace(program->outputs.begin(), program->outputs.end(), (*I), newOutput); program->outputs.pop_back(); graphExit->block->addStatement(ShStatement( ShVariable(newOutput), SH_OP_ASN, ShVariable(varMap[*I]))); } ShContext::current()->exit(); ShVariableReplacer replacer(varMap); program->ctrlGraph->dfs(replacer); program->collectVariables(); optimize(program); return program; } ShProgram combine(ShProgram pa, ShProgram pb) { ShProgramNodePtr a = pa.node(); ShProgramNodePtr b = pb.node(); std::string rtarget; if( !a || !b ) SH_DEBUG_WARN( "Connecting with a null ShProgram" ); if (!a) return b; if (!b) return a; if (a->target().empty()) { rtarget = b->target(); // A doesn't have a target. Use b's. } else { if (b->target().empty() || a->target() == b->target()) { rtarget = a->target(); // A has a target, b doesn't } else { rtarget = ""; // Connecting different targets. } } ShProgramNodePtr program = new ShProgramNode(rtarget); ShCtrlGraphNodePtr heada, taila, headb, tailb; a->ctrlGraph->copy(heada, taila); b->ctrlGraph->copy(headb, tailb); taila->append(headb); ShCtrlGraphPtr new_graph = new ShCtrlGraph(heada, tailb); program->ctrlGraph = new_graph; program->inputs = a->inputs; program->inputs.insert(program->inputs.end(), b->inputs.begin(), b->inputs.end()); program->outputs = a->outputs; program->outputs.insert(program->outputs.end(), b->outputs.begin(), b->outputs.end()); program->collectVariables(); optimize(program); return program; } // Duplicates to inputs with matching name/type ShProgram mergeNames(ShProgram p) { typedef std::pair<std::string, int> InputType; typedef std::map< InputType, int > FirstOccurenceMap; // position of first occurence of an input type typedef std::vector< std::vector<int> > Duplicates; FirstOccurenceMap firsts; // dups[i] stores the set of positions that have matching input types with position i. // The whole set is stored in the smallest i position. Duplicates dups( p.node()->inputs.size(), std::vector<int>()); std::size_t i = 0; for(ShProgramNode::VarList::const_iterator I = p.node()->inputs.begin(); I != p.node()->inputs.end(); ++I, ++i) { InputType it( (*I)->name(), (*I)->size() ); if( firsts.find( it ) != firsts.end() ) { // duplicate dups[ firsts[it] ].push_back(i); } else { firsts[it] = i; dups[i].push_back(i); } } std::vector<int> swizzle; ShFixedManipulator duplicator; for(i = 0; i < dups.size(); ++i) { if( dups[i].empty() ) continue; for(std::size_t j = 0; j < dups[i].size(); ++j) swizzle.push_back(dups[i][j]); if( duplicator ) duplicator = duplicator & shDup(dups[i].size()); else duplicator = shDup(dups[i].size()); } ShProgram result = p << shSwizzle(swizzle); if( duplicator ) result = result << duplicator; return result.node(); } ShProgram namedCombine(ShProgram a, ShProgram b) { return mergeNames(combine(a, b)); } ShProgram namedConnect(ShProgram pa, ShProgram pb, bool keepExtra) { ShProgramNodeCPtr a = pa.node(); ShProgramNodeCPtr b = pb.node(); // positions of a pair of matched a output and b input typedef std::map<int, int> MatchedChannelMap; std::vector<bool> aMatch(a->outputs.size(), false); std::vector<bool> bMatch(b->inputs.size(), false); MatchedChannelMap mcm; std::size_t i, j; ShProgramNode::VarList::const_iterator I, J; i = 0; for(I = a->outputs.begin(); I != a->outputs.end(); ++I, ++i) { j = 0; for(J = b->inputs.begin(); J != b->inputs.end(); ++J, ++j) { if(bMatch[j]) continue; if((*I)->name() != (*J)->name()) continue; if((*I)->size() != (*J)->size()) { SH_DEBUG_WARN("Named connect matched channel name " << (*I)->name() << " but output size " << (*I)->size() << " != " << " input size " << (*J)->size() ); continue; } mcm[i] = j; aMatch[i] = true; bMatch[j] = true; } } std::vector<int> swiz(b->inputs.size(), 0); for(MatchedChannelMap::iterator mcmit = mcm.begin(); mcmit != mcm.end(); ++mcmit) { swiz[mcmit->second] = mcmit->first; } // swizzle unmatched inputs and make a pass them through properly ShProgram passer = SH_BEGIN_PROGRAM() {} SH_END; int newInputIdx = a->outputs.size(); // index of next new input added to a for(j = 0, J= b->inputs.begin(); J != b->inputs.end(); ++J, ++j) { if( !bMatch[j] ) { ShProgram passOne = SH_BEGIN_PROGRAM() { ShVariable var((*J)->clone(SH_INOUT)); } SH_END; passer = passer & passOne; swiz[j] = newInputIdx++; } } ShProgram aPass = combine(pa, passer); if( keepExtra ) { for(i = 0; i < aMatch.size(); ++i) { if( !aMatch[i] ) swiz.push_back(i); } } return mergeNames(pb << ( shSwizzle(swiz) << aPass )); } ShProgram renameInput(ShProgram a, const std::string& oldName, const std::string& newName) { ShProgram renamer = SH_BEGIN_PROGRAM() { for(ShProgramNode::VarList::const_iterator I = a.node()->inputs.begin(); I != a.node()->inputs.end(); ++I) { ShVariable var((*I)->clone(SH_INOUT)); if (!(*I)->has_name()) continue; std::string name = (*I)->name(); if( name == oldName ) { var.name(newName); } else { var.name(name); } } } SH_END; return connect(renamer, a); } // TODO factor out common code from renameInput, renameOutput ShProgram renameOutput(ShProgram a, const std::string& oldName, const std::string& newName) { ShProgram renamer = SH_BEGIN_PROGRAM() { for(ShProgramNode::VarList::const_iterator I = a.node()->outputs.begin(); I != a.node()->outputs.end(); ++I) { ShVariable var((*I)->clone(SH_INOUT)); if (!(*I)->has_name()) continue; std::string name = (*I)->name(); if( name == oldName ) { var.name(newName); } else { var.name(name); } } } SH_END; return connect(a, renamer); } ShProgram namedAlign(ShProgram a, ShProgram b) { ShManipulator<std::string> ordering; for(ShProgramNode::VarList::const_iterator I = b.node()->inputs.begin(); I != b.node()->inputs.end(); ++I) { ordering((*I)->name()); } return ordering << a; } ShProgram operator<<(ShProgram a, ShProgram b) { return connect(b,a); } ShProgram operator>>(ShProgram a, ShProgram b) { return connect(a,b); } ShProgram operator&(ShProgram a, ShProgram b) { return combine(a, b); } ShProgram operator>>(ShProgram p, const ShVariable &var) { return replaceVariable(p, var); } ShProgram replaceVariable(ShProgram a, const ShVariable& v) { ShProgram program(a.node()->clone()); ShVarMap varMap; ShContext::current()->enter(program.node()); // make a new input ShVariableNodePtr newInput(v.node()->clone(SH_INPUT)); varMap[v.node()] = newInput; ShContext::current()->exit(); ShVariableReplacer replacer(varMap); program.node()->ctrlGraph->dfs(replacer); optimize(program); return program; } ShProgram operator<<(ShProgram a, const ShVariable& var) { ShProgram vNibble = SH_BEGIN_PROGRAM() { ShVariable out(var.node()->clone(SH_OUTPUT, var.size(), var.valueType(), SH_SEMANTICTYPE_END, true, false)); shASN(out, var); } SH_END_PROGRAM; return connect(vNibble, a); } } <|endoftext|>
<commit_before>/* * gl_shader.cpp * * Created on: 24.05.2012 * */ #include "graphics/gl_extensions.h" #include "graphics/utils/gl_shader.h" #include <stdio.h> #include "scripts/LuaConfig.h" #include <map> #include "config.h" #include "safestring.h" #include "hacks.h" #include "debug.h" #include <cmath> //#define M_LOG2E 1.44269504088896340736 //log2(e) extern MainConfig conf; ShaderConfigAttributes::~ShaderConfigAttributes() { free( name ); } ShaderConfigData::~ShaderConfigData() { if( vertex_name ) free( vertex_name ); if( fragment_name ) free( fragment_name ); if( name ) free( name ); if( output ){ for( unsigned int i = 0; i < output_count; ++i ) free( output[i] ); free( output ); } if( attributes ) delete[] attributes; } namespace { char* filetobuf( const char* file ) { FILE *fptr; long length; char *buf; fptr = fopen(file, "rb"); /* Open file for reading */ if (!fptr) /* Return NULL on failure */ return NULL; fseek(fptr, 0, SEEK_END); /* Seek to the end of the file */ length = ftell(fptr); /* Find out how many bytes into the file we are */ buf = (char*)malloc(length+1); /* Allocate a buffer for the entire length of the file and a null terminator */ fseek(fptr, 0, SEEK_SET); /* Go back to the beginning of the file */ fread(buf, length, 1, fptr); /* Read the contents of the file in to the buffer */ fclose(fptr); /* Close the file */ buf[length] = 0; /* Null terminator */ return buf; /* Return the buffer */ } std::map< enum GLSFlags, GLuint > shaders[glpLast]; std::map< enum GLSFlags, UniformHandlers > uniforms[glpLast]; int macro_size = 0; char** macro_names = NULL; } char* generate_defines( enum GLSFlags glflags ) { unsigned int size = sizeof(char); int string_size = 1; char* str = (char*)malloc( size ); str[0] = '\0'; const char* def = "#define "; int def_size = strlen(def) + 1; unsigned int flag = glsFirst; int index = -1; while( flag < glsAll ){ ++index; flag <<= 1; if( ( glflags & flag ) == 0 || index > macro_size ) continue; const char* decl = macro_names[index]; if( !decl ) continue; string_size += def_size + strlen(decl); str = (char*)realloc( str, size * string_size ); strcat( str, def ); strcat( str, decl ); strcat( str, "\n" ); } return str; } bool get_iv( GLint* status, GLuint object, int type, int name ) { switch( type ){ case GL_COMPILE_STATUS: glGetShaderiv( object, name, status ); break; case GL_LINK_STATUS: glGetProgramiv( object, name, status ); break; default: Debug::debug( Debug::GRAPHICS, "Wrong shader operation.\n"); return false; } return true; } bool check_shader( GLuint object, int status_name, const char* name ) { // TODO: rewrite GLint status; if( !get_iv( &status, object, status_name, status_name ) ) return false; if( status == GL_FALSE ){ int log_length; char* info_log; if( !get_iv( &log_length, object, status_name, GL_INFO_LOG_LENGTH ) ) return false; /* The maxLength includes the NULL character */ info_log = (char*)malloc( log_length ); switch( status_name ){ case GL_COMPILE_STATUS: glGetShaderInfoLog( object, log_length, &log_length, info_log ); break; case GL_LINK_STATUS: glGetProgramInfoLog( object, log_length, &log_length, info_log ); break; default: free( info_log ); Debug::debug( Debug::GRAPHICS, "Wrong shader operation.\n"); return false; } Debug::debug( Debug::GRAPHICS, "%s: %s.\n", name, info_log ); /* Handle the error in an appropriate way such as displaying a message or writing to a log file. */ /* In this simple program, we'll just leave */ free(info_log); return false; } return true; } GLint create_shader( const char* filename, int type, const char* defines ) { /* Pointer will receive the contents of our shader source code files */ char* buffer = filetobuf( filename ); if( buffer == NULL ){ Debug::debug( Debug::OS, "Shader file not found: %s.\n", filename ); return -1; } int size = 8 + strlen(filename); char* name = (char*)malloc( (unsigned)sizeof(char) * size ); snprintf( name, size, "Shader %s", filename ); const char* sources[2] = { defines, buffer }; /* Create an empty shader handle */ GLuint shader = glCreateShader( type ); /* Send the shader source code to GL */ /* Note that the source code is NULL character terminated. */ /* GL will automatically detect that therefore the length info can be 0 in this case (the last parameter) */ glShaderSource( shader, 2, sources, 0 ); /* Compile the shader */ glCompileShader( shader ); if( !check_shader( shader, GL_COMPILE_STATUS, name ) ){ glDeleteShader(shader); shader = -1; } // Free allocated resources free(name); free(buffer); return shader; } GLuint createProgram( enum GLSPass pass, enum GLSFlags glflags ) { char* defines = generate_defines( glflags ); // Get data from config file ShaderConfigData config; // Push shader config to stack and load config; LuaConfig* cfg = new LuaConfig(); std::string shd_id = "shader_" + citoa(pass); cfg->pushSubconfig( shd_id.c_str(), "shader"); int conf_loaded = cfg->LuaMain::getValue( -1, config ); // Remove shader config from stack; cfg->pop( 1 ); delete cfg; if( !conf_loaded ) return 0; GLint vertex = create_shader( (conf.path.shaders + config.vertex_name).c_str(), GL_VERTEX_SHADER, defines ); GLint fragment = create_shader( (conf.path.shaders + config.fragment_name).c_str(), GL_FRAGMENT_SHADER, defines ); free( defines ); if( vertex < 0 || fragment < 0 ) return 0; /* If we reached this point it means the vertex and fragment shaders compiled and are syntax error free. */ /* We must link them together to make a GL shader program */ /* GL shader programs are monolithic. It is a single piece made of 1 vertex shader and 1 fragment shader. */ /* Assign our program handle a "name" */ GLuint shaderprogram = glCreateProgram(); /* Attach our shaders to our program */ glAttachShader( shaderprogram, vertex ); glAttachShader( shaderprogram, fragment ); /* Bind attribute indexes to locations */ /* Attribute locations must be setup before calling glLinkProgram. */ for( unsigned int i = 0; i < config.attributes_count; ++i ) glBindAttribLocation( shaderprogram, config.attributes[i].index, config.attributes[i].name ); /* Bind fragment outputs indexes to locations */ for( unsigned int i = 0; i < config.output_count; ++i ) glBindFragDataLocation( shaderprogram, i, config.output[i] ); /* Link our program */ /* At this stage, the vertex and fragment programs are inspected, optimized and a binary code is generated for the shader. */ /* The binary code is uploaded to the GPU, if there is no error. */ glLinkProgram( shaderprogram ); /* Cleanup all the things we bound and allocated */ #ifndef DEBUG_SHADERS glDetachShader( shaderprogram, vertex ); glDetachShader( shaderprogram, fragment ); glDeleteShader( vertex ); glDeleteShader( fragment ); #endif /* Again, we must check and make sure that it linked. If it fails, it would mean either there is a mismatch between the vertex */ /* and fragment shaders. It might be that you have surpassed your GPU's abilities. Perhaps too many ALU operations or */ /* too many texel fetch instructions or too many interpolators or dynamic loops. */ char program_string[ strlen(config.name) + 17 ]; sprintf( program_string, "Shader program %s", config.name ); if( !check_shader( shaderprogram, GL_LINK_STATUS, program_string ) ){ glDeleteProgram( shaderprogram ); return 0; } GLint uniforms_count; glGetProgramiv( shaderprogram, GL_ACTIVE_UNIFORMS, &uniforms_count ); UniformHandlers& hdl = uniforms[pass][glflags]; hdl.count = uniforms_count; if( hdl.count ) hdl.handlers = new UniformHandler[hdl.count]; for( UINT i = 0; i < hdl.count; ++i ){ int name_len = 0, num = 0; char name[100]; UniformHandler* h = &hdl.handlers[i]; glGetActiveUniform( shaderprogram, i, sizeof(name)-1, &name_len, &num, &h->type, name ); name[name_len] = '\0'; h->location = glGetUniformLocation( shaderprogram, name ); h->index = UniformsManager::register_uniform( name, h->type ); } return shaderprogram; } void Shaders::init( ) { LuaConfig* cfg = new LuaConfig(); unsigned int flag = glsFirst; int index = -1; char buf[15]; // log2(x ) : log(x) / log(2); floor to not count last element macro_size = floor( log(glsLast) * M_LOG2E ); macro_names = (char**)malloc( (UINT)sizeof(char*) * macro_size ); while( flag < glsAll ){ ++index; flag <<= 1; sprintf( buf, "shadermacro_%d", flag ); macro_names[index] = NULL; cfg->getValue( "name", buf, macro_names[index] ); } delete cfg; } void Shaders::clean( ) { for( int i = 0; i < glpLast; ++i ){ FOREACHIT1( uniforms[i] ){ UniformHandlers& h = (*it).second; delete[] h.handlers; } } } GLuint Shaders::getProgram( enum GLSPass pass, enum GLSFlags glflags ) { if( pass == glpNone ) return 0; std::map< enum GLSFlags, GLuint >& shaders_map = shaders[pass]; std::map< enum GLSFlags, GLuint >::iterator fit = shaders_map.find( glflags ); if( fit != shaders_map.end() ) return fit->second; GLuint prog = createProgram( pass, glflags ); if( prog ){ shaders_map[glflags] = prog; } return prog; } UniformHandlers* Shaders::getUniforms( enum GLSPass pass, enum GLSFlags glflags ) { if( pass == glpNone ) return NULL; std::map< enum GLSFlags, UniformHandlers >& uniforms_map = uniforms[pass]; std::map< enum GLSFlags, UniformHandlers >::iterator fit = uniforms_map.find( glflags ); if( fit != uniforms_map.end() ) return &fit->second; return NULL; } <commit_msg>Version is first string.<commit_after>/* * gl_shader.cpp * * Created on: 24.05.2012 * */ #include "graphics/gl_extensions.h" #include "graphics/utils/gl_shader.h" #include <stdio.h> #include "scripts/LuaConfig.h" #include <map> #include "config.h" #include "safestring.h" #include "hacks.h" #include "debug.h" #include <cmath> //#define M_LOG2E 1.44269504088896340736 //log2(e) extern MainConfig conf; ShaderConfigAttributes::~ShaderConfigAttributes() { free( name ); } ShaderConfigData::~ShaderConfigData() { if( vertex_name ) free( vertex_name ); if( fragment_name ) free( fragment_name ); if( name ) free( name ); if( output ){ for( unsigned int i = 0; i < output_count; ++i ) free( output[i] ); free( output ); } if( attributes ) delete[] attributes; } namespace { char* filetobuf( const char* file ) { FILE *fptr; long length; char *buf; fptr = fopen(file, "rb"); /* Open file for reading */ if (!fptr) /* Return NULL on failure */ return NULL; fseek(fptr, 0, SEEK_END); /* Seek to the end of the file */ length = ftell(fptr); /* Find out how many bytes into the file we are */ buf = (char*)malloc(length+1); /* Allocate a buffer for the entire length of the file and a null terminator */ fseek(fptr, 0, SEEK_SET); /* Go back to the beginning of the file */ fread(buf, length, 1, fptr); /* Read the contents of the file in to the buffer */ fclose(fptr); /* Close the file */ buf[length] = 0; /* Null terminator */ return buf; /* Return the buffer */ } int extract_version( char** version, char* buffer ) { char* tmpbuf = strdup( buffer ); char* endl = strtok( tmpbuf, "\n" ); while( strncmp( tmpbuf, "#version", 8 ) != 0 && endl ) endl = strtok( NULL, "\n" ); // End of this line if( !endl ) return 0; int len = strlen(tmpbuf); int vlen = len + 2; int buflen = strlen(buffer) - vlen; *version = (char*)malloc(vlen); strncpy( *version, tmpbuf, vlen ); (*version)[len] = '\n'; memmove( buffer, buffer + vlen, buflen ); memset( &buffer[buflen], '\0', vlen ); free(tmpbuf); return buflen; } std::map< enum GLSFlags, GLuint > shaders[glpLast]; std::map< enum GLSFlags, UniformHandlers > uniforms[glpLast]; int macro_size = 0; char** macro_names = NULL; } char* generate_defines( enum GLSFlags glflags ) { unsigned int size = sizeof(char); int string_size = 1; char* str = (char*)malloc( size ); str[0] = '\0'; const char* def = "#define "; int def_size = strlen(def) + 1; unsigned int flag = glsFirst; int index = -1; while( flag < glsAll ){ ++index; flag <<= 1; if( ( glflags & flag ) == 0 || index > macro_size ) continue; const char* decl = macro_names[index]; if( !decl ) continue; string_size += def_size + strlen(decl); str = (char*)realloc( str, size * string_size ); strcat( str, def ); strcat( str, decl ); strcat( str, "\n" ); } return str; } bool get_iv( GLint* status, GLuint object, int type, int name ) { switch( type ){ case GL_COMPILE_STATUS: glGetShaderiv( object, name, status ); break; case GL_LINK_STATUS: glGetProgramiv( object, name, status ); break; default: Debug::debug( Debug::GRAPHICS, "Wrong shader operation.\n"); return false; } return true; } bool check_shader( GLuint object, int status_name, const char* name ) { // TODO: rewrite GLint status; if( !get_iv( &status, object, status_name, status_name ) ) return false; if( status == GL_FALSE ){ int log_length; char* info_log; if( !get_iv( &log_length, object, status_name, GL_INFO_LOG_LENGTH ) ) return false; /* The maxLength includes the NULL character */ info_log = (char*)malloc( log_length ); switch( status_name ){ case GL_COMPILE_STATUS: glGetShaderInfoLog( object, log_length, &log_length, info_log ); break; case GL_LINK_STATUS: glGetProgramInfoLog( object, log_length, &log_length, info_log ); break; default: free( info_log ); Debug::debug( Debug::GRAPHICS, "Wrong shader operation.\n"); return false; } Debug::debug( Debug::GRAPHICS, "%s: %s.\n", name, info_log ); /* Handle the error in an appropriate way such as displaying a message or writing to a log file. */ /* In this simple program, we'll just leave */ free(info_log); return false; } return true; } GLint create_shader( const char* filename, int type, const char* defines ) { char* version = NULL; /* Pointer will receive the contents of our shader source code files */ char* buffer = filetobuf( filename ); if( buffer == NULL ){ Debug::debug( Debug::OS, "Shader file not found: %s.\n", filename ); return -1; } if( !extract_version( &version, buffer ) ){ free(buffer); Debug::debug( Debug::OS, "Shader version not specified in file %s.\n", filename ); return -1; } int size = 8 + strlen(filename); char* name = (char*)malloc( (unsigned)sizeof(char) * size ); snprintf( name, size, "Shader %s", filename ); const char* sources[3] = { version, defines, buffer }; /* Create an empty shader handle */ GLuint shader = glCreateShader( type ); /* Send the shader source code to GL */ /* Note that the source code is NULL character terminated. */ /* GL will automatically detect that therefore the length info can be 0 in this case (the last parameter) */ glShaderSource( shader, 3, sources, 0 ); /* Compile the shader */ glCompileShader( shader ); if( !check_shader( shader, GL_COMPILE_STATUS, name ) ){ glDeleteShader(shader); shader = -1; } // Free allocated resources free(name); free(version); free(buffer); return shader; } GLuint createProgram( enum GLSPass pass, enum GLSFlags glflags ) { char* defines = generate_defines( glflags ); // Get data from config file ShaderConfigData config; // Push shader config to stack and load config; LuaConfig* cfg = new LuaConfig(); std::string shd_id = "shader_" + citoa(pass); cfg->pushSubconfig( shd_id.c_str(), "shader"); int conf_loaded = cfg->LuaMain::getValue( -1, config ); // Remove shader config from stack; cfg->pop( 1 ); delete cfg; if( !conf_loaded ) return 0; GLint vertex = create_shader( (conf.path.shaders + config.vertex_name).c_str(), GL_VERTEX_SHADER, defines ); GLint fragment = create_shader( (conf.path.shaders + config.fragment_name).c_str(), GL_FRAGMENT_SHADER, defines ); free( defines ); if( vertex < 0 || fragment < 0 ) return 0; /* If we reached this point it means the vertex and fragment shaders compiled and are syntax error free. */ /* We must link them together to make a GL shader program */ /* GL shader programs are monolithic. It is a single piece made of 1 vertex shader and 1 fragment shader. */ /* Assign our program handle a "name" */ GLuint shaderprogram = glCreateProgram(); /* Attach our shaders to our program */ glAttachShader( shaderprogram, vertex ); glAttachShader( shaderprogram, fragment ); /* Bind attribute indexes to locations */ /* Attribute locations must be setup before calling glLinkProgram. */ for( unsigned int i = 0; i < config.attributes_count; ++i ) glBindAttribLocation( shaderprogram, config.attributes[i].index, config.attributes[i].name ); /* Bind fragment outputs indexes to locations */ for( unsigned int i = 0; i < config.output_count; ++i ) glBindFragDataLocation( shaderprogram, i, config.output[i] ); /* Link our program */ /* At this stage, the vertex and fragment programs are inspected, optimized and a binary code is generated for the shader. */ /* The binary code is uploaded to the GPU, if there is no error. */ glLinkProgram( shaderprogram ); /* Cleanup all the things we bound and allocated */ #ifndef DEBUG_SHADERS glDetachShader( shaderprogram, vertex ); glDetachShader( shaderprogram, fragment ); glDeleteShader( vertex ); glDeleteShader( fragment ); #endif /* Again, we must check and make sure that it linked. If it fails, it would mean either there is a mismatch between the vertex */ /* and fragment shaders. It might be that you have surpassed your GPU's abilities. Perhaps too many ALU operations or */ /* too many texel fetch instructions or too many interpolators or dynamic loops. */ char program_string[ strlen(config.name) + 17 ]; sprintf( program_string, "Shader program %s", config.name ); if( !check_shader( shaderprogram, GL_LINK_STATUS, program_string ) ){ glDeleteProgram( shaderprogram ); return 0; } GLint uniforms_count; glGetProgramiv( shaderprogram, GL_ACTIVE_UNIFORMS, &uniforms_count ); UniformHandlers& hdl = uniforms[pass][glflags]; hdl.count = uniforms_count; if( hdl.count ) hdl.handlers = new UniformHandler[hdl.count]; for( UINT i = 0; i < hdl.count; ++i ){ int name_len = 0, num = 0; char name[100]; UniformHandler* h = &hdl.handlers[i]; glGetActiveUniform( shaderprogram, i, sizeof(name)-1, &name_len, &num, &h->type, name ); name[name_len] = '\0'; h->location = glGetUniformLocation( shaderprogram, name ); h->index = UniformsManager::register_uniform( name, h->type ); } return shaderprogram; } void Shaders::init( ) { LuaConfig* cfg = new LuaConfig(); unsigned int flag = glsFirst; int index = -1; char buf[15]; // log2(x ) : log(x) / log(2); floor to not count last element macro_size = floor( log(glsLast) * M_LOG2E ); macro_names = (char**)malloc( (UINT)sizeof(char*) * macro_size ); while( flag < glsAll ){ ++index; flag <<= 1; sprintf( buf, "shadermacro_%d", flag ); macro_names[index] = NULL; cfg->getValue( "name", buf, macro_names[index] ); } delete cfg; } void Shaders::clean( ) { for( int i = 0; i < glpLast; ++i ){ FOREACHIT1( uniforms[i] ){ UniformHandlers& h = (*it).second; delete[] h.handlers; } } } GLuint Shaders::getProgram( enum GLSPass pass, enum GLSFlags glflags ) { if( pass == glpNone ) return 0; std::map< enum GLSFlags, GLuint >& shaders_map = shaders[pass]; std::map< enum GLSFlags, GLuint >::iterator fit = shaders_map.find( glflags ); if( fit != shaders_map.end() ) return fit->second; GLuint prog = createProgram( pass, glflags ); if( prog ){ shaders_map[glflags] = prog; } return prog; } UniformHandlers* Shaders::getUniforms( enum GLSPass pass, enum GLSFlags glflags ) { if( pass == glpNone ) return NULL; std::map< enum GLSFlags, UniformHandlers >& uniforms_map = uniforms[pass]; std::map< enum GLSFlags, UniformHandlers >::iterator fit = uniforms_map.find( glflags ); if( fit != uniforms_map.end() ) return &fit->second; return NULL; } <|endoftext|>
<commit_before>#include "ledostalker.h" #include <QThread> #include <QDebug> class LEDOSTalkerPrivate { public: LEDOSTalkerPrivate() { serial = NULL; } ~LEDOSTalkerPrivate() { if( serial != NULL && serial->isOpen() ) serial->close(); } QSerialPort *serial; }; LEDOSTalker::LEDOSTalker(QObject *parent) : d_ptr(new LEDOSTalkerPrivate) { } void LEDOSTalker::serial(QString portName) { if( d_ptr->serial != NULL && d_ptr->serial->portName() != portName && d_ptr->serial->isOpen() ) d_ptr->serial->close(); d_ptr->serial = new QSerialPort(portName); d_ptr->serial->setBaudRate(115200); d_ptr->serial->open(QSerialPort::WriteOnly); QThread::msleep(1000); d_ptr->serial->write("effect activecolor\n"); d_ptr->serial->flush(); } void LEDOSTalker::color(QColor color) { QString command = QString("b%1%2%3\n"); command = command.arg(color.red(), 2, 16, QChar('0')); command = command.arg(color.green(), 2, 16, QChar('0')); command = command.arg(color.blue(), 2, 16, QChar('0')); // qDebug() << command; d_ptr->serial->write( command.toStdString().c_str() ); d_ptr->serial->flush(); } <commit_msg>Dropped activecolor for just color<commit_after>#include "ledostalker.h" #include <QThread> #include <QDebug> class LEDOSTalkerPrivate { public: LEDOSTalkerPrivate() { serial = NULL; } ~LEDOSTalkerPrivate() { if( serial != NULL && serial->isOpen() ) serial->close(); } QSerialPort *serial; }; LEDOSTalker::LEDOSTalker(QObject *parent) : d_ptr(new LEDOSTalkerPrivate) { } void LEDOSTalker::serial(QString portName) { if( d_ptr->serial != NULL && d_ptr->serial->portName() != portName && d_ptr->serial->isOpen() ) d_ptr->serial->close(); d_ptr->serial = new QSerialPort(portName); d_ptr->serial->setBaudRate(115200); d_ptr->serial->open(QSerialPort::WriteOnly); QThread::msleep(1000); d_ptr->serial->write("effect color\n"); d_ptr->serial->flush(); } void LEDOSTalker::color(QColor color) { QString command = QString("b%1%2%3\n"); command = command.arg(color.red(), 2, 16, QChar('0')); command = command.arg(color.green(), 2, 16, QChar('0')); command = command.arg(color.blue(), 2, 16, QChar('0')); // qDebug() << command; d_ptr->serial->write( command.toStdString().c_str() ); d_ptr->serial->flush(); } <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.commontk.org/LICENSE Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QDebug> // CTK includes #include "ctkLogger.h" #include "ctkVTKScalarsToColorsView.h" #include "ctkVTKVolumePropertyWidget.h" #include "ctkUtils.h" #include "ui_ctkVTKVolumePropertyWidget.h" // VTK includes #include <vtkColorTransferControlPointsItem.h> #include <vtkColorTransferFunction.h> #include <vtkColorTransferFunctionItem.h> #include <vtkCompositeControlPointsItem.h> #include <vtkCompositeTransferFunctionItem.h> #include <vtkContextScene.h> #include <vtkLookupTable.h> #include <vtkLookupTableItem.h> #include <vtkPiecewiseControlPointsItem.h> #include <vtkPiecewiseFunction.h> #include <vtkPiecewiseFunctionItem.h> #include <vtkVolumeProperty.h> //---------------------------------------------------------------------------- static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKVolumePropertyWidget"); //---------------------------------------------------------------------------- class ctkVTKVolumePropertyWidgetPrivate: public Ui_ctkVTKVolumePropertyWidget { Q_DECLARE_PUBLIC(ctkVTKVolumePropertyWidget); protected: ctkVTKVolumePropertyWidget* const q_ptr; public: ctkVTKVolumePropertyWidgetPrivate(ctkVTKVolumePropertyWidget& object); void setupUi(QWidget* widget); void computeRange(double* range); void updateThresholdSlider(vtkPiecewiseFunction* opacityFunction); void setThreshold(double min, double max, double opacity); vtkVolumeProperty* VolumeProperty; int CurrentComponent; }; // ---------------------------------------------------------------------------- // ctkVTKVolumePropertyWidgetPrivate methods // ---------------------------------------------------------------------------- ctkVTKVolumePropertyWidgetPrivate::ctkVTKVolumePropertyWidgetPrivate( ctkVTKVolumePropertyWidget& object) : q_ptr(&object) { this->VolumeProperty = 0; this->CurrentComponent = 0; } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidgetPrivate::setupUi(QWidget* widget) { Q_Q(ctkVTKVolumePropertyWidget); Q_ASSERT(q == widget); this->Ui_ctkVTKVolumePropertyWidget::setupUi(widget); this->ScalarOpacityWidget->view()->addCompositeFunction(0, 0, true, true); vtkCompositeControlPointsItem* composite = vtkCompositeControlPointsItem::SafeDownCast( this->ScalarOpacityWidget->view()->opacityFunctionPlots()[1]); composite->SetColorFill(true); composite->SetPointsFunction(vtkCompositeControlPointsItem::OpacityPointsFunction); composite->SetPointsFunction(vtkCompositeControlPointsItem::ColorPointsFunction); this->ScalarColorWidget->view()->addColorTransferFunction(0); this->GradientWidget->view()->addPiecewiseFunction(0); this->ScalarOpacityThresholdWidget->setVisible(false); QObject::connect(this->ScalarOpacityWidget, SIGNAL(axesModified()), q, SLOT(onAxesModified()));//, Qt::QueuedConnection); QObject::connect(this->ScalarColorWidget, SIGNAL(axesModified()), q, SLOT(onAxesModified()));//, Qt::QueuedConnection); QObject::connect(this->GradientWidget, SIGNAL(axesModified()), q, SLOT(onAxesModified()));//, Qt::QueuedConnection); this->GradientGroupBox->setCollapsed(true); this->AdvancedGroupBox->setCollapsed(true); QObject::connect(this->InterpolationComboBox, SIGNAL(currentIndexChanged(int)), q, SLOT(setInterpolationMode(int))); QObject::connect(this->ShadeCheckBox, SIGNAL(toggled(bool)), q, SLOT(setShade(bool))); QObject::connect(this->MaterialPropertyWidget, SIGNAL(ambientChanged(double)), q, SLOT(setAmbient(double))); QObject::connect(this->MaterialPropertyWidget, SIGNAL(diffuseChanged(double)), q, SLOT(setDiffuse(double))); QObject::connect(this->MaterialPropertyWidget, SIGNAL(specularChanged(double)), q, SLOT(setSpecular(double))); QObject::connect(this->MaterialPropertyWidget, SIGNAL(specularPowerChanged(double)), q, SLOT(setSpecularPower(double))); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidgetPrivate::computeRange(double* range) { range[0] = 0.; range[1] = 1.; if (!this->VolumeProperty) { return; } Q_ASSERT(this->VolumeProperty->GetRGBTransferFunction(this->CurrentComponent)); Q_ASSERT(this->VolumeProperty->GetScalarOpacity(this->CurrentComponent)); Q_ASSERT(this->VolumeProperty->GetGradientOpacity(this->CurrentComponent)); double colorRange[2] = {0., 1.}; this->VolumeProperty->GetRGBTransferFunction(this->CurrentComponent)->GetRange(colorRange); range[0] = qMin(range[0], colorRange[0]); range[1] = qMax(range[1], colorRange[1]); double opacityRange[2] = {0., 1.}; this->VolumeProperty->GetScalarOpacity(this->CurrentComponent)->GetRange(opacityRange); range[0] = qMin(range[0], opacityRange[0]); range[1] = qMax(range[1], opacityRange[1]); double gradientRange[2] = {0., 1.}; this->VolumeProperty->GetGradientOpacity(this->CurrentComponent)->GetRange(gradientRange); range[0] = qMin(range[0], gradientRange[0]); range[1] = qMax(range[1], gradientRange[1]); } // ---------------------------------------------------------------------------- // ctkVTKVolumePropertyWidget methods // ---------------------------------------------------------------------------- ctkVTKVolumePropertyWidget::ctkVTKVolumePropertyWidget(QWidget* parentWidget) :QWidget(parentWidget) , d_ptr(new ctkVTKVolumePropertyWidgetPrivate(*this)) { Q_D(ctkVTKVolumePropertyWidget); d->setupUi(this); } // ---------------------------------------------------------------------------- ctkVTKVolumePropertyWidget::~ctkVTKVolumePropertyWidget() { } // ---------------------------------------------------------------------------- vtkVolumeProperty* ctkVTKVolumePropertyWidget::volumeProperty()const { Q_D(const ctkVTKVolumePropertyWidget); return d->VolumeProperty; } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget ::setVolumeProperty(vtkVolumeProperty* newVolumeProperty) { Q_D(ctkVTKVolumePropertyWidget); this->qvtkReconnect(d->VolumeProperty, newVolumeProperty, vtkCommand::ModifiedEvent, this, SLOT(updateFromVolumeProperty())); d->VolumeProperty = newVolumeProperty; this->updateFromVolumeProperty(); double range[2]; d->computeRange(range); d->ScalarOpacityThresholdWidget->setRange(range[0], range[1]); double chartBounds[8]; d->ScalarOpacityWidget->view()->chartBounds(chartBounds); chartBounds[2] = range[0]; chartBounds[3] = range[1]; d->ScalarOpacityWidget->view()->setChartUserBounds(chartBounds); d->ScalarColorWidget->view()->chartBounds(chartBounds); chartBounds[2] = range[0]; chartBounds[3] = range[1]; d->ScalarColorWidget->view()->setChartUserBounds(chartBounds); d->GradientWidget->view()->chartBounds(chartBounds); chartBounds[2] = range[0]; chartBounds[3] = range[1]; d->GradientWidget->view()->setChartUserBounds(chartBounds); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::updateFromVolumeProperty() { Q_D(ctkVTKVolumePropertyWidget); vtkColorTransferFunction* colorTransferFunction = 0; vtkPiecewiseFunction* opacityFunction = 0; vtkPiecewiseFunction* gradientFunction = 0; if (d->VolumeProperty) { colorTransferFunction = d->VolumeProperty->GetRGBTransferFunction()->GetSize() ? d->VolumeProperty->GetRGBTransferFunction() : 0; opacityFunction = d->VolumeProperty->GetScalarOpacity()->GetSize() ? d->VolumeProperty->GetScalarOpacity() : 0; gradientFunction = d->VolumeProperty->GetGradientOpacity()->GetSize() ? d->VolumeProperty->GetGradientOpacity() : 0; } d->ScalarOpacityThresholdWidget->setPiecewiseFunction(this->useThresholdSlider() ? opacityFunction : 0); d->ScalarOpacityWidget->view()->setOpacityFunctionToPlots(opacityFunction); d->ScalarOpacityWidget->view()->setColorTransferFunctionToPlots(colorTransferFunction); d->ScalarColorWidget->view()->setColorTransferFunctionToPlots(colorTransferFunction); d->GradientWidget->view()->setPiecewiseFunctionToPlots(gradientFunction); if (d->VolumeProperty) { d->InterpolationComboBox->setCurrentIndex( d->VolumeProperty->GetInterpolationType() == VTK_NEAREST_INTERPOLATION ? 0 : 1); d->ShadeCheckBox->setChecked( d->VolumeProperty->GetShade(d->CurrentComponent)); d->MaterialPropertyWidget->setAmbient( d->VolumeProperty->GetAmbient(d->CurrentComponent)); d->MaterialPropertyWidget->setDiffuse( d->VolumeProperty->GetDiffuse(d->CurrentComponent)); d->MaterialPropertyWidget->setSpecular( d->VolumeProperty->GetSpecular(d->CurrentComponent)); d->MaterialPropertyWidget->setSpecularPower( d->VolumeProperty->GetSpecularPower(d->CurrentComponent)); } } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setInterpolationMode(int mode) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetInterpolationType(mode); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setShade(bool enable) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetShade(d->CurrentComponent, enable); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setAmbient(double value) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetAmbient(d->CurrentComponent, value); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setDiffuse(double value) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetDiffuse(d->CurrentComponent, value); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setSpecular(double value) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetSpecular(d->CurrentComponent, value); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setSpecularPower(double value) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetSpecularPower(d->CurrentComponent, value); } // ---------------------------------------------------------------------------- bool ctkVTKVolumePropertyWidget::useThresholdSlider()const { Q_D(const ctkVTKVolumePropertyWidget); return d->ScalarOpacityThresholdWidget->isVisibleTo( const_cast<ctkVTKVolumePropertyWidget*>(this)); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setUseThresholdSlider(bool enable) { Q_D(ctkVTKVolumePropertyWidget); d->ScalarOpacityThresholdWidget->setVisible(enable); d->ScalarOpacityWidget->setVisible(!enable); this->updateFromVolumeProperty(); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::onAxesModified() { Q_D(ctkVTKVolumePropertyWidget); //return; ctkVTKScalarsToColorsWidget* senderWidget = qobject_cast<ctkVTKScalarsToColorsWidget*>(this->sender()); double xRange[2] = {0.,0.}; senderWidget->xRange(xRange); if (senderWidget != d->ScalarOpacityWidget) { bool wasBlocking = d->ScalarOpacityWidget->blockSignals(true); d->ScalarOpacityWidget->setXRange(xRange[0], xRange[1]); d->ScalarOpacityWidget->blockSignals(wasBlocking); } if (senderWidget != d->ScalarColorWidget) { bool wasBlocking = d->ScalarColorWidget->blockSignals(true); d->ScalarColorWidget->setXRange(xRange[0], xRange[1]); d->ScalarColorWidget->blockSignals(wasBlocking); } if (senderWidget != d->GradientWidget) { bool wasBlocking = d->GradientWidget->blockSignals(true); d->GradientWidget->setXRange(xRange[0], xRange[1]); d->GradientWidget->blockSignals(wasBlocking); } } <commit_msg>Forgot to remove ColorPointsFunction<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.commontk.org/LICENSE Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QDebug> // CTK includes #include "ctkLogger.h" #include "ctkVTKScalarsToColorsView.h" #include "ctkVTKVolumePropertyWidget.h" #include "ctkUtils.h" #include "ui_ctkVTKVolumePropertyWidget.h" // VTK includes #include <vtkColorTransferControlPointsItem.h> #include <vtkColorTransferFunction.h> #include <vtkColorTransferFunctionItem.h> #include <vtkCompositeControlPointsItem.h> #include <vtkCompositeTransferFunctionItem.h> #include <vtkContextScene.h> #include <vtkLookupTable.h> #include <vtkLookupTableItem.h> #include <vtkPiecewiseControlPointsItem.h> #include <vtkPiecewiseFunction.h> #include <vtkPiecewiseFunctionItem.h> #include <vtkVolumeProperty.h> //---------------------------------------------------------------------------- static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKVolumePropertyWidget"); //---------------------------------------------------------------------------- class ctkVTKVolumePropertyWidgetPrivate: public Ui_ctkVTKVolumePropertyWidget { Q_DECLARE_PUBLIC(ctkVTKVolumePropertyWidget); protected: ctkVTKVolumePropertyWidget* const q_ptr; public: ctkVTKVolumePropertyWidgetPrivate(ctkVTKVolumePropertyWidget& object); void setupUi(QWidget* widget); void computeRange(double* range); void updateThresholdSlider(vtkPiecewiseFunction* opacityFunction); void setThreshold(double min, double max, double opacity); vtkVolumeProperty* VolumeProperty; int CurrentComponent; }; // ---------------------------------------------------------------------------- // ctkVTKVolumePropertyWidgetPrivate methods // ---------------------------------------------------------------------------- ctkVTKVolumePropertyWidgetPrivate::ctkVTKVolumePropertyWidgetPrivate( ctkVTKVolumePropertyWidget& object) : q_ptr(&object) { this->VolumeProperty = 0; this->CurrentComponent = 0; } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidgetPrivate::setupUi(QWidget* widget) { Q_Q(ctkVTKVolumePropertyWidget); Q_ASSERT(q == widget); this->Ui_ctkVTKVolumePropertyWidget::setupUi(widget); this->ScalarOpacityWidget->view()->addCompositeFunction(0, 0, true, true); vtkCompositeControlPointsItem* composite = vtkCompositeControlPointsItem::SafeDownCast( this->ScalarOpacityWidget->view()->opacityFunctionPlots()[1]); composite->SetColorFill(true); composite->SetPointsFunction(vtkCompositeControlPointsItem::OpacityPointsFunction); this->ScalarColorWidget->view()->addColorTransferFunction(0); this->GradientWidget->view()->addPiecewiseFunction(0); this->ScalarOpacityThresholdWidget->setVisible(false); QObject::connect(this->ScalarOpacityWidget, SIGNAL(axesModified()), q, SLOT(onAxesModified()));//, Qt::QueuedConnection); QObject::connect(this->ScalarColorWidget, SIGNAL(axesModified()), q, SLOT(onAxesModified()));//, Qt::QueuedConnection); QObject::connect(this->GradientWidget, SIGNAL(axesModified()), q, SLOT(onAxesModified()));//, Qt::QueuedConnection); this->GradientGroupBox->setCollapsed(true); this->AdvancedGroupBox->setCollapsed(true); QObject::connect(this->InterpolationComboBox, SIGNAL(currentIndexChanged(int)), q, SLOT(setInterpolationMode(int))); QObject::connect(this->ShadeCheckBox, SIGNAL(toggled(bool)), q, SLOT(setShade(bool))); QObject::connect(this->MaterialPropertyWidget, SIGNAL(ambientChanged(double)), q, SLOT(setAmbient(double))); QObject::connect(this->MaterialPropertyWidget, SIGNAL(diffuseChanged(double)), q, SLOT(setDiffuse(double))); QObject::connect(this->MaterialPropertyWidget, SIGNAL(specularChanged(double)), q, SLOT(setSpecular(double))); QObject::connect(this->MaterialPropertyWidget, SIGNAL(specularPowerChanged(double)), q, SLOT(setSpecularPower(double))); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidgetPrivate::computeRange(double* range) { range[0] = 0.; range[1] = 1.; if (!this->VolumeProperty) { return; } Q_ASSERT(this->VolumeProperty->GetRGBTransferFunction(this->CurrentComponent)); Q_ASSERT(this->VolumeProperty->GetScalarOpacity(this->CurrentComponent)); Q_ASSERT(this->VolumeProperty->GetGradientOpacity(this->CurrentComponent)); double colorRange[2] = {0., 1.}; this->VolumeProperty->GetRGBTransferFunction(this->CurrentComponent)->GetRange(colorRange); range[0] = qMin(range[0], colorRange[0]); range[1] = qMax(range[1], colorRange[1]); double opacityRange[2] = {0., 1.}; this->VolumeProperty->GetScalarOpacity(this->CurrentComponent)->GetRange(opacityRange); range[0] = qMin(range[0], opacityRange[0]); range[1] = qMax(range[1], opacityRange[1]); double gradientRange[2] = {0., 1.}; this->VolumeProperty->GetGradientOpacity(this->CurrentComponent)->GetRange(gradientRange); range[0] = qMin(range[0], gradientRange[0]); range[1] = qMax(range[1], gradientRange[1]); } // ---------------------------------------------------------------------------- // ctkVTKVolumePropertyWidget methods // ---------------------------------------------------------------------------- ctkVTKVolumePropertyWidget::ctkVTKVolumePropertyWidget(QWidget* parentWidget) :QWidget(parentWidget) , d_ptr(new ctkVTKVolumePropertyWidgetPrivate(*this)) { Q_D(ctkVTKVolumePropertyWidget); d->setupUi(this); } // ---------------------------------------------------------------------------- ctkVTKVolumePropertyWidget::~ctkVTKVolumePropertyWidget() { } // ---------------------------------------------------------------------------- vtkVolumeProperty* ctkVTKVolumePropertyWidget::volumeProperty()const { Q_D(const ctkVTKVolumePropertyWidget); return d->VolumeProperty; } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget ::setVolumeProperty(vtkVolumeProperty* newVolumeProperty) { Q_D(ctkVTKVolumePropertyWidget); this->qvtkReconnect(d->VolumeProperty, newVolumeProperty, vtkCommand::ModifiedEvent, this, SLOT(updateFromVolumeProperty())); d->VolumeProperty = newVolumeProperty; this->updateFromVolumeProperty(); double range[2]; d->computeRange(range); d->ScalarOpacityThresholdWidget->setRange(range[0], range[1]); double chartBounds[8]; d->ScalarOpacityWidget->view()->chartBounds(chartBounds); chartBounds[2] = range[0]; chartBounds[3] = range[1]; d->ScalarOpacityWidget->view()->setChartUserBounds(chartBounds); d->ScalarColorWidget->view()->chartBounds(chartBounds); chartBounds[2] = range[0]; chartBounds[3] = range[1]; d->ScalarColorWidget->view()->setChartUserBounds(chartBounds); d->GradientWidget->view()->chartBounds(chartBounds); chartBounds[2] = range[0]; chartBounds[3] = range[1]; d->GradientWidget->view()->setChartUserBounds(chartBounds); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::updateFromVolumeProperty() { Q_D(ctkVTKVolumePropertyWidget); vtkColorTransferFunction* colorTransferFunction = 0; vtkPiecewiseFunction* opacityFunction = 0; vtkPiecewiseFunction* gradientFunction = 0; if (d->VolumeProperty) { colorTransferFunction = d->VolumeProperty->GetRGBTransferFunction()->GetSize() ? d->VolumeProperty->GetRGBTransferFunction() : 0; opacityFunction = d->VolumeProperty->GetScalarOpacity()->GetSize() ? d->VolumeProperty->GetScalarOpacity() : 0; gradientFunction = d->VolumeProperty->GetGradientOpacity()->GetSize() ? d->VolumeProperty->GetGradientOpacity() : 0; } d->ScalarOpacityThresholdWidget->setPiecewiseFunction(this->useThresholdSlider() ? opacityFunction : 0); d->ScalarOpacityWidget->view()->setOpacityFunctionToPlots(opacityFunction); d->ScalarOpacityWidget->view()->setColorTransferFunctionToPlots(colorTransferFunction); d->ScalarColorWidget->view()->setColorTransferFunctionToPlots(colorTransferFunction); d->GradientWidget->view()->setPiecewiseFunctionToPlots(gradientFunction); if (d->VolumeProperty) { d->InterpolationComboBox->setCurrentIndex( d->VolumeProperty->GetInterpolationType() == VTK_NEAREST_INTERPOLATION ? 0 : 1); d->ShadeCheckBox->setChecked( d->VolumeProperty->GetShade(d->CurrentComponent)); d->MaterialPropertyWidget->setAmbient( d->VolumeProperty->GetAmbient(d->CurrentComponent)); d->MaterialPropertyWidget->setDiffuse( d->VolumeProperty->GetDiffuse(d->CurrentComponent)); d->MaterialPropertyWidget->setSpecular( d->VolumeProperty->GetSpecular(d->CurrentComponent)); d->MaterialPropertyWidget->setSpecularPower( d->VolumeProperty->GetSpecularPower(d->CurrentComponent)); } } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setInterpolationMode(int mode) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetInterpolationType(mode); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setShade(bool enable) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetShade(d->CurrentComponent, enable); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setAmbient(double value) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetAmbient(d->CurrentComponent, value); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setDiffuse(double value) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetDiffuse(d->CurrentComponent, value); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setSpecular(double value) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetSpecular(d->CurrentComponent, value); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setSpecularPower(double value) { Q_D(ctkVTKVolumePropertyWidget); if (!d->VolumeProperty) { return; } d->VolumeProperty->SetSpecularPower(d->CurrentComponent, value); } // ---------------------------------------------------------------------------- bool ctkVTKVolumePropertyWidget::useThresholdSlider()const { Q_D(const ctkVTKVolumePropertyWidget); return d->ScalarOpacityThresholdWidget->isVisibleTo( const_cast<ctkVTKVolumePropertyWidget*>(this)); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::setUseThresholdSlider(bool enable) { Q_D(ctkVTKVolumePropertyWidget); d->ScalarOpacityThresholdWidget->setVisible(enable); d->ScalarOpacityWidget->setVisible(!enable); this->updateFromVolumeProperty(); } // ---------------------------------------------------------------------------- void ctkVTKVolumePropertyWidget::onAxesModified() { Q_D(ctkVTKVolumePropertyWidget); //return; ctkVTKScalarsToColorsWidget* senderWidget = qobject_cast<ctkVTKScalarsToColorsWidget*>(this->sender()); double xRange[2] = {0.,0.}; senderWidget->xRange(xRange); if (senderWidget != d->ScalarOpacityWidget) { bool wasBlocking = d->ScalarOpacityWidget->blockSignals(true); d->ScalarOpacityWidget->setXRange(xRange[0], xRange[1]); d->ScalarOpacityWidget->blockSignals(wasBlocking); } if (senderWidget != d->ScalarColorWidget) { bool wasBlocking = d->ScalarColorWidget->blockSignals(true); d->ScalarColorWidget->setXRange(xRange[0], xRange[1]); d->ScalarColorWidget->blockSignals(wasBlocking); } if (senderWidget != d->GradientWidget) { bool wasBlocking = d->GradientWidget->blockSignals(true); d->GradientWidget->setXRange(xRange[0], xRange[1]); d->GradientWidget->blockSignals(wasBlocking); } } <|endoftext|>
<commit_before>#include<iostream> #include<vector> #include<cstdio> #include<string> #include<thread> #include<dirent.h> #include<chrono> #include<sys/socket.h> #include<netinet/in.h> #include<sys/types.h> #include<arpa/inet.h> #include<fcntl.h> #include<unistd.h> #include<cstdlib> #include<sys/wait.h> #include<string.h> #include<mutex> #include<unordered_map> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <iterator> #define SUCCESS 0 #define FAILURE 1 #define MAX_SIZE 1024 #define CLI_ID "101" #define TOKEN "#" //#define BCAST_PORT 6000 //#define LISTENER_PORT 54545 #define BCAST_PORT 54545 #define LISTENER_PORT 6000 struct node_config_object{ char *node_id; char *node_ip; char *node_port; int buffer; int timer; }; template<typename Out> void split(const std::string &s, char delim, Out result) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } void nodeBootSequence(struct node_config_object *nodeID) { std::ifstream ConfigFile; ConfigFile.open("../config/config"); std::string data; while(getline(ConfigFile, data)) { if(data == "") { continue; } else { std::cout<<data<<std::endl; std::vector<std::string> x = split(data, '='); for (auto i: x) { std::cout << i << std::endl; } } } } /* FILE *config_file; char line[255]; string TempBuffer; config_file = fopen("../config/config","r"); while(fgets(line,sizeof(line),config_file)) { if(line[0]=='#'|| (!(strcmp(line,""))) ) continue; else { std::cout<<line<<std::endl; } } */ //std::fstream config_file; //char line[255]; //config_file.open("../config/config",std::ios::in|std::ios::out); /* while(config_file.getline(line,255)) { if('\n'==line[0]) continue; else { std::cout<<line<<std::endl; char* ip =strtok(line,"="); //cluster_info[ip]=port; } } */ void fs_bcast() { //Current Client Socket int bcast_sockfd; bcast_sockfd = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in new_addr; memset(&new_addr, 0, sizeof(new_addr)); new_addr.sin_family = AF_INET; new_addr.sin_port = BCAST_PORT; new_addr.sin_addr.s_addr = htonl(INADDR_ANY); while(1) { std::cout << "....................................." << std::endl; std::cout << "... Now Broadcasting Node Content ..." << std::endl; std::cout << "....................................." << std::endl; /* Broadcast Every 10 Seconds (Configurable) */ std::this_thread::sleep_for(std::chrono::milliseconds(3000)); /* Get files in Directory and create a FS Packet*/ DIR *dir; struct dirent *ent; char fs_data[MAX_SIZE]; memset(fs_data, 0, MAX_SIZE); strcpy(fs_data, CLI_ID); if ((dir = opendir ("../files")) != NULL) { while((ent = readdir (dir)) != NULL) { if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) {continue;} else { strcat(fs_data, TOKEN); strcat(fs_data, ent->d_name); } } } closedir (dir); std::cout << "--> "<< fs_data << std::endl; //Need to implment for loop over all Socket fd to send file info sendto(bcast_sockfd, fs_data, strlen(fs_data), 0, (struct sockaddr *)&new_addr, sizeof(struct sockaddr_in)); } } void bcast_listener() { /* Client Address */ struct sockaddr_in recv_client_addr; unsigned slen = sizeof(recv_client_addr); /* listener Address */ int sockfd; struct sockaddr_in listener_addr; sockfd = socket(AF_INET, SOCK_DGRAM, 0); memset(&listener_addr, 0, sizeof(listener_addr)); listener_addr.sin_family = AF_INET; listener_addr.sin_port = LISTENER_PORT; listener_addr.sin_addr.s_addr = htonl(INADDR_ANY); int bind_status = bind(sockfd, (struct sockaddr*)&listener_addr, sizeof(listener_addr)); while(1) { std::cout << "Listening ..." << std::endl; char bcast_buffer[MAX_SIZE]; memset(bcast_buffer, 0, sizeof(bcast_buffer)); recvfrom(sockfd, bcast_buffer, sizeof(bcast_buffer)-1, 0, (sockaddr *)&recv_client_addr, &slen); std::cout << "Listening.." <<std::endl; std::cout << "GOT FS" << bcast_buffer << std::endl; } } int main(int argc, char **argv) { /* Configuration Parsing */ struct node_config_object *nodeID; nodeID = (struct node_config_object*)malloc(sizeof(node_config_object)); nodeBootSequence(nodeID); /* Start Broadcaseting Thread */ std::thread broadcaster(fs_bcast); /* Start BroadCast Listener */ std::thread listener(bcast_listener); /* Make them independent */ broadcaster.detach(); listener.detach(); while(1){} return SUCCESS; } <commit_msg>Initial Boot UP parsing Done!<commit_after>#include<iostream> #include<vector> #include<cstdio> #include<string> #include<thread> #include<dirent.h> #include<chrono> #include<sys/socket.h> #include<netinet/in.h> #include<sys/types.h> #include<arpa/inet.h> #include<fcntl.h> #include<unistd.h> #include<cstdlib> #include<sys/wait.h> #include<string.h> #include<mutex> #include<unordered_map> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <iterator> //#include "fs_header.h" #define SUCCESS 0 #define FAILURE 1 #define MAX_SIZE 1024 #define CLI_ID "101" #define TOKEN "#" //#define BCAST_PORT 6000 //#define LISTENER_PORT 54545 #define BCAST_PORT 54545 #define LISTENER_PORT 6000 struct node_config_object{ char *node_id; char *node_ip; char *node_port; char *buffer; char *timer; char *listener_port; }; template<typename Out> void split(const std::string &s, char delim, Out result) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } void nodeBootSequence(struct node_config_object *nodeObj) { FILE *config_file = NULL; char line[150]; int line_size = 150; config_file = fopen("../config/config","r"); while (fgets(line, line_size, config_file)) { if(line[0]=='#') { continue; } else { std::cout<<line<<std::endl; char *temp1 = NULL; char *temp2 = NULL; temp1 = strtok(line,"="); std::cout<<temp1<<std::endl; if(strcmp(temp1,"NODE_ID") == 0){ temp2 = strtok(NULL,"="); nodeObj->node_id = strdup(temp2); } if(strcmp(temp1,"NODE_IP_ADDRESS") == 0){ temp2 = strtok(NULL,"="); nodeObj->node_ip = strdup(temp2); } if(strcmp(temp1,"NODE_PORT_ADDRESS") == 0){ temp2 = strtok(NULL,"="); nodeObj->node_port = strdup(temp2); } if(strcmp(temp1,"MAX_BUFF") == 0){ temp2 = strtok(NULL,"="); nodeObj->buffer = strdup(temp2); } if(strcmp(temp1,"FS_DURATION") == 0){ temp2 = strtok(NULL,"="); nodeObj->timer = strdup(temp2); } if(strcmp(temp1,"LISTNER_PORT") == 0){ temp2 = strtok(NULL,"="); nodeObj->listener_port = strdup(temp2); } } } } void fs_bcast() { //Current Client Socket int bcast_sockfd; bcast_sockfd = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in new_addr; memset(&new_addr, 0, sizeof(new_addr)); new_addr.sin_family = AF_INET; new_addr.sin_port = BCAST_PORT; new_addr.sin_addr.s_addr = htonl(INADDR_ANY); while(1) { std::cout << "....................................." << std::endl; std::cout << "... Now Broadcasting Node Content ..." << std::endl; std::cout << "....................................." << std::endl; /* Broadcast Every 10 Seconds (Configurable) */ std::this_thread::sleep_for(std::chrono::milliseconds(3000)); /* Get files in Directory and create a FS Packet*/ DIR *dir; struct dirent *ent; char fs_data[MAX_SIZE]; memset(fs_data, 0, MAX_SIZE); strcpy(fs_data, CLI_ID); if ((dir = opendir ("../files")) != NULL) { while((ent = readdir (dir)) != NULL) { if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) {continue;} else { strcat(fs_data, TOKEN); strcat(fs_data, ent->d_name); } } } closedir (dir); std::cout << "--> "<< fs_data << std::endl; //Need to implment for loop over all Socket fd to send file info sendto(bcast_sockfd, fs_data, strlen(fs_data), 0, (struct sockaddr *)&new_addr, sizeof(struct sockaddr_in)); } } void bcast_listener() { /* Client Address */ struct sockaddr_in recv_client_addr; unsigned slen = sizeof(recv_client_addr); /* listener Address */ int sockfd; struct sockaddr_in listener_addr; sockfd = socket(AF_INET, SOCK_DGRAM, 0); memset(&listener_addr, 0, sizeof(listener_addr)); listener_addr.sin_family = AF_INET; listener_addr.sin_port = LISTENER_PORT; listener_addr.sin_addr.s_addr = htonl(INADDR_ANY); int bind_status = bind(sockfd, (struct sockaddr*)&listener_addr, sizeof(listener_addr)); while(1) { std::cout << "Listening ..." << std::endl; char bcast_buffer[MAX_SIZE]; memset(bcast_buffer, 0, sizeof(bcast_buffer)); recvfrom(sockfd, bcast_buffer, sizeof(bcast_buffer)-1, 0, (sockaddr *)&recv_client_addr, &slen); std::cout << "Listening.." <<std::endl; std::cout << "GOT FS" << bcast_buffer << std::endl; } } int main(int argc, char **argv) { /* Configuration Parsing */ struct node_config_object *nodeObj; nodeObj = (struct node_config_object*)malloc(sizeof(node_config_object)); nodeBootSequence(nodeObj); std::cout << "========================="<<nodeObj->node_id; std::cout << "========================="<<nodeObj->node_ip; std::cout << "========================="<<nodeObj->node_port; std::cout << "========================="<<nodeObj->buffer; std::cout << "========================="<<nodeObj->timer; std::cout << "========================="<<nodeObj->listener_port; /* Start Broadcaseting Thread */ std::thread broadcaster(fs_bcast); /* Start BroadCast Listener */ std::thread listener(bcast_listener); /* Make them independent */ broadcaster.detach(); listener.detach(); while(1){} return SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/system/input_device_settings.h" #include <stdarg.h> #include <string> #include <vector> #include "base/bind.h" #include "base/chromeos/chromeos_version.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/stringprintf.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/browser_thread.h" namespace chromeos { namespace system { namespace { const char kTpControl[] = "/opt/google/touchpad/tpcontrol"; const char kMouseControl[] = "/opt/google/mouse/mousecontrol"; bool ScriptExists(const std::string& script) { return file_util::PathExists(FilePath(script)); } // Executes the input control script asynchronously, if it exists. void ExecuteScriptOnFileThread(const std::vector<std::string>& argv) { DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); DCHECK(!argv.empty()); const std::string& script(argv[0]); // Script must exist on device. DCHECK(!base::chromeos::IsRunningOnChromeOS() || ScriptExists(script)); if (!ScriptExists(script)) return; base::LaunchOptions options; options.wait = true; base::LaunchProcess(CommandLine(argv), options, NULL); } void ExecuteScript(int argc, ...) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); std::vector<std::string> argv; va_list vl; va_start(vl, argc); for (int i = 0; i < argc; ++i) { argv.push_back(va_arg(vl, const char*)); } va_end(vl); content::BrowserThread::GetBlockingPool()->PostTask(FROM_HERE, base::Bind(&ExecuteScriptOnFileThread, argv)); } void SetPointerSensitivity(const char* script, int value) { DCHECK(value > 0 && value < 6); ExecuteScript(3, script, "sensitivity", StringPrintf("%d", value).c_str()); } bool DeviceExists(const char* script) { DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); if (!ScriptExists(script)) return false; std::vector<std::string> argv; argv.push_back(script); argv.push_back("status"); std::string output; // Output is empty if the device is not found. return base::GetAppOutput(CommandLine(argv), &output) && !output.empty(); } } // namespace namespace touchpad_settings { bool TouchpadExists() { // We only need to do this check once, assuming no pluggable touchpad devices. DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); static bool init = false; static bool exists = false; if (!init) { init = true; exists = DeviceExists(kTpControl); } return exists; } // Sets the touchpad sensitivity in the range [1, 5]. void SetSensitivity(int value) { SetPointerSensitivity(kTpControl, value); } void SetTapToClick(bool enabled) { ExecuteScript(3, kTpControl, "taptoclick", enabled ? "on" : "off"); } void SetThreeFingerClick(bool enabled) { ExecuteScript(3, kTpControl, "three_finger_click", enabled ? "on" : "off"); // For Alex/ZGB. ExecuteScript(3, kTpControl, "t5r2_three_finger_click", enabled ? "on" : "off"); } } // namespace touchpad_settings namespace mouse_settings { bool MouseExists() { return DeviceExists(kMouseControl); } // Sets the touchpad sensitivity in the range [1, 5]. void SetSensitivity(int value) { SetPointerSensitivity(kMouseControl, value); } void SetPrimaryButtonRight(bool right) { ExecuteScript(3, kMouseControl, "swap_left_right", right ? "1" : "0"); } } // namespace mouse_settings } // namespace system } // namespace chromeos <commit_msg>Revert 162899 - Use BlockingPool instead of FILE thread to excecute scripts.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/system/input_device_settings.h" #include <stdarg.h> #include <string> #include <vector> #include "base/bind.h" #include "base/chromeos/chromeos_version.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/stringprintf.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; namespace chromeos { namespace system { namespace { const char kTpControl[] = "/opt/google/touchpad/tpcontrol"; const char kMouseControl[] = "/opt/google/mouse/mousecontrol"; bool ScriptExists(const std::string& script) { return file_util::PathExists(FilePath(script)); } // Executes the input control script asynchronously, if it exists. void ExecuteScriptOnFileThread(const std::vector<std::string>& argv) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); DCHECK(!argv.empty()); const std::string& script(argv[0]); // Script must exist on device. DCHECK(!base::chromeos::IsRunningOnChromeOS() || ScriptExists(script)); if (!ScriptExists(script)) return; base::LaunchOptions options; options.wait = true; base::LaunchProcess(CommandLine(argv), options, NULL); } void ExecuteScript(int argc, ...) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); std::vector<std::string> argv; va_list vl; va_start(vl, argc); for (int i = 0; i < argc; ++i) { argv.push_back(va_arg(vl, const char*)); } va_end(vl); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&ExecuteScriptOnFileThread, argv)); } void SetPointerSensitivity(const char* script, int value) { DCHECK(value > 0 && value < 6); ExecuteScript(3, script, "sensitivity", StringPrintf("%d", value).c_str()); } bool DeviceExists(const char* script) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!ScriptExists(script)) return false; std::vector<std::string> argv; argv.push_back(script); argv.push_back("status"); std::string output; // Output is empty if the device is not found. return base::GetAppOutput(CommandLine(argv), &output) && !output.empty(); } } // namespace namespace touchpad_settings { bool TouchpadExists() { // We only need to do this check once, assuming no pluggable touchpad devices. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); static bool init = false; static bool exists = false; if (!init) { init = true; exists = DeviceExists(kTpControl); } return exists; } // Sets the touchpad sensitivity in the range [1, 5]. void SetSensitivity(int value) { SetPointerSensitivity(kTpControl, value); } void SetTapToClick(bool enabled) { ExecuteScript(3, kTpControl, "taptoclick", enabled ? "on" : "off"); } void SetThreeFingerClick(bool enabled) { ExecuteScript(3, kTpControl, "three_finger_click", enabled ? "on" : "off"); // For Alex/ZGB. ExecuteScript(3, kTpControl, "t5r2_three_finger_click", enabled ? "on" : "off"); } } // namespace touchpad_settings namespace mouse_settings { bool MouseExists() { return DeviceExists(kMouseControl); } // Sets the touchpad sensitivity in the range [1, 5]. void SetSensitivity(int value) { SetPointerSensitivity(kMouseControl, value); } void SetPrimaryButtonRight(bool right) { ExecuteScript(3, kMouseControl, "swap_left_right", right ? "1" : "0"); } } // namespace mouse_settings } // namespace system } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/options/customize_sync_window_gtk.h" #include <gtk/gtk.h> #include <string> #include "app/gtk_signal.h" #include "app/l10n_util.h" #include "base/message_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/gtk/accessible_widget_helper_gtk.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/options_window.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/sync/glue/data_type_controller.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk // // The contents of the Customize Sync dialog window. class CustomizeSyncWindowGtk { public: explicit CustomizeSyncWindowGtk(Profile* profile); ~CustomizeSyncWindowGtk(); void Show(); bool ClickOk(); void ClickCancel(); private: // The pixel width we wrap labels at. static const int kWrapWidth = 475; GtkWidget* AddCheckbox(GtkWidget* parent, int label_id, bool checked); bool Accept(); static void OnWindowDestroy(GtkWidget* widget, CustomizeSyncWindowGtk* window); static void OnResponse(GtkDialog* dialog, gint response_id, CustomizeSyncWindowGtk* customize_sync_window); CHROMEGTK_CALLBACK_0(CustomizeSyncWindowGtk, void, OnCheckboxClicked); // The customize sync dialog. GtkWidget *dialog_; Profile* profile_; GtkWidget* description_label_; GtkWidget* bookmarks_check_box_; GtkWidget* preferences_check_box_; GtkWidget* themes_check_box_; GtkWidget* extensions_check_box_; GtkWidget* autofill_check_box_; // Helper object to manage accessibility metadata. scoped_ptr<AccessibleWidgetHelper> accessible_widget_helper_; DISALLOW_COPY_AND_ASSIGN(CustomizeSyncWindowGtk); }; // The singleton customize sync window object. static CustomizeSyncWindowGtk* customize_sync_window = NULL; /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk, public: CustomizeSyncWindowGtk::CustomizeSyncWindowGtk(Profile* profile) : profile_(profile), description_label_(NULL), bookmarks_check_box_(NULL), preferences_check_box_(NULL), themes_check_box_(NULL), extensions_check_box_(NULL), autofill_check_box_(NULL) { syncable::ModelTypeSet registered_types; profile_->GetProfileSyncService()->GetRegisteredDataTypes(&registered_types); syncable::ModelTypeSet preferred_types; profile_->GetProfileSyncService()->GetPreferredDataTypes(&preferred_types); std::string dialog_name = l10n_util::GetStringUTF8( IDS_CUSTOMIZE_SYNC_WINDOW_TITLE); dialog_ = gtk_dialog_new_with_buttons( dialog_name.c_str(), // Customize sync window is shared between all browser windows. NULL, // Non-modal. GTK_DIALOG_NO_SEPARATOR, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, NULL); gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), gtk_util::kContentAreaSpacing); accessible_widget_helper_.reset(new AccessibleWidgetHelper( dialog_, profile)); accessible_widget_helper_->SendOpenWindowNotification(dialog_name); GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); description_label_ = gtk_label_new(l10n_util::GetStringUTF8( IDS_CUSTOMIZE_SYNC_DESCRIPTION).c_str()); gtk_label_set_line_wrap(GTK_LABEL(description_label_), TRUE); gtk_widget_set_size_request(description_label_, kWrapWidth, -1); gtk_box_pack_start(GTK_BOX(vbox), description_label_, FALSE, FALSE, 0); accessible_widget_helper_->SetWidgetName(description_label_, IDS_CUSTOMIZE_SYNC_DESCRIPTION); DCHECK(registered_types.count(syncable::BOOKMARKS)); bool bookmarks_checked = preferred_types.count(syncable::BOOKMARKS) != 0; bookmarks_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_BOOKMARKS, bookmarks_checked); if (registered_types.count(syncable::PREFERENCES)) { bool prefs_checked = preferred_types.count(syncable::PREFERENCES) != 0; preferences_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_PREFERENCES, prefs_checked); } if (registered_types.count(syncable::THEMES)) { bool themes_checked = preferred_types.count(syncable::THEMES) != 0; themes_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_THEMES, themes_checked); } if (registered_types.count(syncable::EXTENSIONS)) { bool extensions_checked = preferred_types.count(syncable::EXTENSIONS) != 0; extensions_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_EXTENSIONS, extensions_checked); } if (registered_types.count(syncable::AUTOFILL)) { bool autofill_checked = preferred_types.count(syncable::AUTOFILL) != 0; autofill_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_AUTOFILL, autofill_checked); } gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), vbox, FALSE, FALSE, 0); gtk_widget_realize(dialog_); gtk_util::SetWindowSizeFromResources(GTK_WINDOW(dialog_), IDS_CUSTOMIZE_SYNC_DIALOG_WIDTH_CHARS, IDS_CUSTOMIZE_SYNC_DIALOG_HEIGHT_LINES, true); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this); g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this); gtk_util::ShowDialog(dialog_); } CustomizeSyncWindowGtk::~CustomizeSyncWindowGtk() { } void CustomizeSyncWindowGtk::Show() { // Bring options window to front if it already existed and isn't already // in front gtk_util::PresentWindow(dialog_, 0); } bool CustomizeSyncWindowGtk::ClickOk() { if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) || (preferences_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( preferences_check_box_))) || (themes_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) || (extensions_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( extensions_check_box_))) || (autofill_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_)))) { Accept(); gtk_widget_destroy(GTK_WIDGET(dialog_)); return true; } else { // show the user that something's wrong with this dialog (not perfect, but // a temporary fix) gtk_util::PresentWindow(dialog_, 0); return false; } } void CustomizeSyncWindowGtk::ClickCancel() { gtk_widget_destroy(GTK_WIDGET(dialog_)); } /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk, private: GtkWidget* CustomizeSyncWindowGtk::AddCheckbox(GtkWidget* parent, int label_id, bool checked) { GtkWidget* checkbox = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(label_id).c_str()); gtk_box_pack_start(GTK_BOX(parent), checkbox, FALSE, FALSE, 0); accessible_widget_helper_->SetWidgetName(checkbox, label_id); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox), checked); g_signal_connect(checkbox, "clicked", G_CALLBACK(OnCheckboxClickedThunk), this); return checkbox; } bool CustomizeSyncWindowGtk::Accept() { syncable::ModelTypeSet preferred_types; bool bookmarks_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(bookmarks_check_box_)); if (bookmarks_enabled) { preferred_types.insert(syncable::BOOKMARKS); } if (preferences_check_box_) { bool preferences_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(preferences_check_box_)); if (preferences_enabled) { preferred_types.insert(syncable::PREFERENCES); } } if (themes_check_box_) { bool themes_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(themes_check_box_)); if (themes_enabled) { preferred_types.insert(syncable::THEMES); } } if (extensions_check_box_) { bool extensions_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(extensions_check_box_)); if (extensions_enabled) { preferred_types.insert(syncable::EXTENSIONS); } } if (autofill_check_box_) { bool autofill_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(autofill_check_box_)); if (autofill_enabled) { preferred_types.insert(syncable::AUTOFILL); } } profile_->GetProfileSyncService()->ChangePreferredDataTypes(preferred_types); return true; } // static void CustomizeSyncWindowGtk::OnWindowDestroy(GtkWidget* widget, CustomizeSyncWindowGtk* window) { customize_sync_window = NULL; MessageLoop::current()->DeleteSoon(FROM_HERE, window); } // static void CustomizeSyncWindowGtk::OnResponse( GtkDialog* dialog, gint response_id, CustomizeSyncWindowGtk* customize_sync_window) { if (response_id == GTK_RESPONSE_OK) { customize_sync_window->ClickOk(); } else if (response_id == GTK_RESPONSE_CANCEL) { customize_sync_window->ClickCancel(); } } // Deactivate the "OK" button if you uncheck all the data types. void CustomizeSyncWindowGtk::OnCheckboxClicked(GtkWidget* widget) { bool any_datatypes_selected = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) || (preferences_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( preferences_check_box_))) || (themes_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) || (extensions_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( extensions_check_box_))) || (autofill_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_))); if (any_datatypes_selected) { gtk_dialog_set_response_sensitive( GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, TRUE); } else { gtk_dialog_set_response_sensitive( GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, FALSE); } } /////////////////////////////////////////////////////////////////////////////// // Factory/finder method: void ShowCustomizeSyncWindow(Profile* profile) { DCHECK(profile); // If there's already an existing window, use it. if (!customize_sync_window) { customize_sync_window = new CustomizeSyncWindowGtk(profile); } customize_sync_window->Show(); } bool CustomizeSyncWindowOk() { if (customize_sync_window) { return customize_sync_window->ClickOk(); } else { return true; } } void CustomizeSyncWindowCancel() { if (customize_sync_window) { customize_sync_window->ClickCancel(); } } <commit_msg>linux: Add Typed URLs checkbox for sync UI. Also refactor this code for readability and more chromey style.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/options/customize_sync_window_gtk.h" #include <gtk/gtk.h> #include <string> #include "app/gtk_signal.h" #include "app/l10n_util.h" #include "base/message_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/gtk/accessible_widget_helper_gtk.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/options_window.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/sync/glue/data_type_controller.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk // // The contents of the Customize Sync dialog window. class CustomizeSyncWindowGtk { public: explicit CustomizeSyncWindowGtk(Profile* profile); ~CustomizeSyncWindowGtk(); void Show(); bool ClickOk(); void ClickCancel(); private: // The pixel width we wrap labels at. static const int kWrapWidth = 475; GtkWidget* AddCheckbox(GtkWidget* parent, int label_id, bool checked); bool Accept(); static void OnWindowDestroy(GtkWidget* widget, CustomizeSyncWindowGtk* window); static void OnResponse(GtkDialog* dialog, gint response_id, CustomizeSyncWindowGtk* customize_sync_window); CHROMEGTK_CALLBACK_0(CustomizeSyncWindowGtk, void, OnCheckboxClicked); // Utility methods to safely determine the state of optional checkboxes. static bool BoxChecked(GtkWidget* check_box) { return check_box && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(check_box)); } bool BookmarksChecked() const { return BoxChecked(bookmarks_check_box_); } bool PreferencesChecked() const { return BoxChecked(preferences_check_box_); } bool ThemesChecked() const { return BoxChecked(themes_check_box_); } bool ExtensionsChecked() const { return BoxChecked(extensions_check_box_); } bool AutofillChecked() const { return BoxChecked(autofill_check_box_); } bool TypedUrlsChecked() const { return BoxChecked(typed_urls_check_box_); } // The customize sync dialog. GtkWidget* dialog_; Profile* profile_; GtkWidget* description_label_; GtkWidget* bookmarks_check_box_; GtkWidget* preferences_check_box_; GtkWidget* themes_check_box_; GtkWidget* extensions_check_box_; GtkWidget* autofill_check_box_; GtkWidget* typed_urls_check_box_; // Helper object to manage accessibility metadata. scoped_ptr<AccessibleWidgetHelper> accessible_widget_helper_; DISALLOW_COPY_AND_ASSIGN(CustomizeSyncWindowGtk); }; // The singleton customize sync window object. static CustomizeSyncWindowGtk* customize_sync_window = NULL; /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk, public: CustomizeSyncWindowGtk::CustomizeSyncWindowGtk(Profile* profile) : profile_(profile), description_label_(NULL), bookmarks_check_box_(NULL), preferences_check_box_(NULL), themes_check_box_(NULL), extensions_check_box_(NULL), autofill_check_box_(NULL), typed_urls_check_box_(NULL) { syncable::ModelTypeSet registered_types; profile_->GetProfileSyncService()->GetRegisteredDataTypes(&registered_types); syncable::ModelTypeSet preferred_types; profile_->GetProfileSyncService()->GetPreferredDataTypes(&preferred_types); std::string dialog_name = l10n_util::GetStringUTF8( IDS_CUSTOMIZE_SYNC_WINDOW_TITLE); dialog_ = gtk_dialog_new_with_buttons( dialog_name.c_str(), // Customize sync window is shared between all browser windows. NULL, // Non-modal. GTK_DIALOG_NO_SEPARATOR, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, NULL); gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), gtk_util::kContentAreaSpacing); accessible_widget_helper_.reset(new AccessibleWidgetHelper( dialog_, profile)); accessible_widget_helper_->SendOpenWindowNotification(dialog_name); GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); description_label_ = gtk_label_new(l10n_util::GetStringUTF8( IDS_CUSTOMIZE_SYNC_DESCRIPTION).c_str()); gtk_label_set_line_wrap(GTK_LABEL(description_label_), TRUE); gtk_widget_set_size_request(description_label_, kWrapWidth, -1); gtk_box_pack_start(GTK_BOX(vbox), description_label_, FALSE, FALSE, 0); accessible_widget_helper_->SetWidgetName(description_label_, IDS_CUSTOMIZE_SYNC_DESCRIPTION); DCHECK(registered_types.count(syncable::BOOKMARKS)); bool bookmarks_checked = preferred_types.count(syncable::BOOKMARKS) != 0; bookmarks_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_BOOKMARKS, bookmarks_checked); if (registered_types.count(syncable::PREFERENCES)) { bool prefs_checked = preferred_types.count(syncable::PREFERENCES) != 0; preferences_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_PREFERENCES, prefs_checked); } if (registered_types.count(syncable::THEMES)) { bool themes_checked = preferred_types.count(syncable::THEMES) != 0; themes_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_THEMES, themes_checked); } if (registered_types.count(syncable::EXTENSIONS)) { bool extensions_checked = preferred_types.count(syncable::EXTENSIONS) != 0; extensions_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_EXTENSIONS, extensions_checked); } if (registered_types.count(syncable::AUTOFILL)) { bool autofill_checked = preferred_types.count(syncable::AUTOFILL) != 0; autofill_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_AUTOFILL, autofill_checked); } if (registered_types.count(syncable::TYPED_URLS)) { bool typed_urls_checked = preferred_types.count(syncable::TYPED_URLS) != 0; typed_urls_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_TYPED_URLS, typed_urls_checked); } gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), vbox, FALSE, FALSE, 0); gtk_widget_realize(dialog_); gtk_util::SetWindowSizeFromResources(GTK_WINDOW(dialog_), IDS_CUSTOMIZE_SYNC_DIALOG_WIDTH_CHARS, IDS_CUSTOMIZE_SYNC_DIALOG_HEIGHT_LINES, true); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this); g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this); gtk_util::ShowDialog(dialog_); } CustomizeSyncWindowGtk::~CustomizeSyncWindowGtk() { } void CustomizeSyncWindowGtk::Show() { // Bring options window to front if it already existed and isn't already // in front gtk_util::PresentWindow(dialog_, 0); } bool CustomizeSyncWindowGtk::ClickOk() { if (BookmarksChecked() || PreferencesChecked() || ThemesChecked() || ExtensionsChecked() || AutofillChecked() || TypedUrlsChecked()) { Accept(); gtk_widget_destroy(GTK_WIDGET(dialog_)); return true; } else { // show the user that something's wrong with this dialog (not perfect, but // a temporary fix) gtk_util::PresentWindow(dialog_, 0); return false; } } void CustomizeSyncWindowGtk::ClickCancel() { gtk_widget_destroy(GTK_WIDGET(dialog_)); } /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk, private: GtkWidget* CustomizeSyncWindowGtk::AddCheckbox(GtkWidget* parent, int label_id, bool checked) { GtkWidget* checkbox = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(label_id).c_str()); gtk_box_pack_start(GTK_BOX(parent), checkbox, FALSE, FALSE, 0); accessible_widget_helper_->SetWidgetName(checkbox, label_id); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox), checked); g_signal_connect(checkbox, "clicked", G_CALLBACK(OnCheckboxClickedThunk), this); return checkbox; } bool CustomizeSyncWindowGtk::Accept() { syncable::ModelTypeSet preferred_types; if (BookmarksChecked()) preferred_types.insert(syncable::BOOKMARKS); if (PreferencesChecked()) preferred_types.insert(syncable::PREFERENCES); if (ThemesChecked()) preferred_types.insert(syncable::THEMES); if (ExtensionsChecked()) preferred_types.insert(syncable::EXTENSIONS); if (AutofillChecked()) preferred_types.insert(syncable::AUTOFILL); if (TypedUrlsChecked()) preferred_types.insert(syncable::TYPED_URLS); profile_->GetProfileSyncService()->ChangePreferredDataTypes(preferred_types); return true; } // static void CustomizeSyncWindowGtk::OnWindowDestroy(GtkWidget* widget, CustomizeSyncWindowGtk* window) { customize_sync_window = NULL; MessageLoop::current()->DeleteSoon(FROM_HERE, window); } // static void CustomizeSyncWindowGtk::OnResponse( GtkDialog* dialog, gint response_id, CustomizeSyncWindowGtk* customize_sync_window) { if (response_id == GTK_RESPONSE_OK) customize_sync_window->ClickOk(); else if (response_id == GTK_RESPONSE_CANCEL) customize_sync_window->ClickCancel(); } // Deactivate the "OK" button if you uncheck all the data types. void CustomizeSyncWindowGtk::OnCheckboxClicked(GtkWidget* widget) { if (BookmarksChecked() || PreferencesChecked() || ThemesChecked() || ExtensionsChecked() || AutofillChecked() || TypedUrlsChecked()) { gtk_dialog_set_response_sensitive( GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, TRUE); } else { gtk_dialog_set_response_sensitive( GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, FALSE); } } /////////////////////////////////////////////////////////////////////////////// // Factory/finder method: void ShowCustomizeSyncWindow(Profile* profile) { DCHECK(profile); // If there's already an existing window, use it. if (!customize_sync_window) customize_sync_window = new CustomizeSyncWindowGtk(profile); customize_sync_window->Show(); } bool CustomizeSyncWindowOk() { if (customize_sync_window) return customize_sync_window->ClickOk(); return true; } void CustomizeSyncWindowCancel() { if (customize_sync_window) customize_sync_window->ClickCancel(); } <|endoftext|>
<commit_before>#ifndef TOKENIZER_H #define TOKENIZER_H #include <list> #include <string> #include <stdexcept> #include <sstream> #include <iterator> namespace sexp_cpp { class Tokenizer { public: std::list<std::string> Tokenize(const std::string& input) { std::string code = input; if(code.empty()) { throw std::invalid_argument("can't tokenize empty string!"); } //replace(code, "(", " ( "); //replace(code, ")", " ) "); std::list<std::string> list; std::istringstream ss(code); list.insert(list.end(), std::istream_iterator<std::string>(ss), std::istream_iterator<std::string>()); return list; } //private: //void replace(std::string& string, const std::string& from, const std::string& to) //{ //size_t i = 0; //size_t next = 0; //while ((next = string.find(from, i)) != std::string::npos) //{ //string.replace(next, from.size(), to); //i = next + to.size(); //} //} }; } // sexp_cpp #endif // TOKENIZER_H <commit_msg>removing dead code<commit_after>#ifndef TOKENIZER_H #define TOKENIZER_H #include <list> #include <string> #include <stdexcept> #include <sstream> #include <iterator> namespace sexp_cpp { class Tokenizer { public: std::list<std::string> Tokenize(const std::string& input) { std::string code = input; if(code.empty()) { throw std::invalid_argument("can't tokenize empty string!"); } std::list<std::string> list; std::istringstream ss(code); list.insert(list.end(), std::istream_iterator<std::string>(ss), std::istream_iterator<std::string>()); return list; } }; } // sexp_cpp #endif // TOKENIZER_H <|endoftext|>
<commit_before> #include <climits> #include <cstdlib> #include <exception> #include <sstream> #include "Utilities.h" #if defined(_MSC_VER) #include <windows.h> #include <Shlwapi.h> #include <vector> #endif std::string getAbsolutePath(const std::string &path) { std::string result = ""; #if defined(_MSC_VER) result.resize(MAX_PATH,' '); SetLastError(0); GetFullPathName(path.c_str(), result.size(), &result[0], nullptr); if (GetLastError()) throw std::runtime_error("Could not determine absolute path of file."); if (!PathFileExists(result.c_str())) result = ""; #else char *abs = realpath(path.c_str(), NULL); if (abs) { result = std::string(abs); free(abs); } #endif return result; } std::string absolutePath(const std::string &path) { std::string result = getAbsolutePath(path); if (result.empty()) { std::stringstream ss; ss << "Could not find file or directory \"" << path << "\"."; throw std::runtime_error(ss.str()); } return result; }<commit_msg>Resize the absolute path string in order to avoid strange effects when using it in string streams later on.<commit_after> #include <climits> #include <cstdlib> #include <exception> #include <sstream> #include "Utilities.h" #if defined(_MSC_VER) #include <windows.h> #include <Shlwapi.h> #include <vector> #endif std::string getAbsolutePath(const std::string &path) { std::string result = ""; #if defined(_MSC_VER) result.resize(MAX_PATH,' '); SetLastError(0); size_t numBytes = GetFullPathName(path.c_str(), result.size(), &result[0], nullptr); result.resize(numBytes); if (GetLastError()) throw std::runtime_error("Could not determine absolute path of file."); if (!PathFileExists(result.c_str())) result = ""; #else char *abs = realpath(path.c_str(), NULL); if (abs) { result = std::string(abs); free(abs); } #endif return result; } std::string absolutePath(const std::string &path) { std::string result = getAbsolutePath(path); if (result.empty()) { std::stringstream ss; ss << "Could not find file or directory \"" << path << "\"."; throw std::runtime_error(ss.str()); } return result; }<|endoftext|>
<commit_before>#include "incline_mgr.h" #include "incline_dbms.h" #include "incline_driver_standalone.h" #include "incline_util.h" using namespace std; vector<string> incline_driver_standalone::insert_trigger_of(const string& src_table) const { vector<string> body; for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_master_of(src_table)) { incline_util::push_back(body, _build_insert_from_def(def, src_table, act_insert)); } } return mgr_->build_trigger_stmt(src_table, "INSERT", body); } vector<string> incline_driver_standalone::update_trigger_of(const string& src_table) const { vector<string> body; for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_dependent_of(src_table)) { if (def->is_master_of(src_table)) { if (! def->npk_columns().empty()) { incline_util::push_back(body, _build_insert_from_def(def, src_table, act_update)); } } else { incline_util::push_back(body, _build_update_merge_from_def(def, src_table)); } } } return mgr_->build_trigger_stmt(src_table, "UPDATE", body); } vector<string> incline_driver_standalone::delete_trigger_of(const string& src_table) const { vector<string> body; for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_master_of(src_table)) { incline_util::push_back(body, _build_delete_from_def(def, src_table)); } } return mgr_->build_trigger_stmt(src_table, "DELETE", body); } vector<string> incline_driver_standalone::_build_insert_from_def(const incline_def* def, const string& src_table, action_t action, const vector<string>* _cond) const { string sql = _build_insert_from_def(def, def->destination(), src_table, action, _cond, NULL); return incline_util::vectorize(sql); } vector<string> incline_driver_standalone::_build_delete_from_def(const incline_def* def, const string& src_table, const vector<string>& _cond) const { vector<string> cond(_cond); for (map<string, string>::const_iterator pi = def->pk_columns().begin(); pi != def->pk_columns().end(); ++pi) { if (incline_def::table_of_column(pi->first) == src_table) { cond.push_back(pi->second + "=OLD." + pi->first.substr(src_table.size() + 1)); } } string sql = "DELETE FROM " + def->destination() + " WHERE " + incline_util::join(" AND ", cond); return incline_util::vectorize(sql); } vector<string> incline_driver_standalone::_build_update_merge_from_def(const incline_def* def, const string& src_table, const vector<string>& _cond) const { vector<string> set_expr, cond(_cond); for (map<string, string>::const_iterator ci = def->columns().begin(); ci != def->columns().end(); ++ci) { if (incline_def::table_of_column(ci->first) == src_table) { set_expr.push_back(ci->second + "=NEW." + ci->first.substr(src_table.size() + 1)); } } incline_util::push_back(cond, _merge_cond_of(def, src_table)); string sql = "UPDATE " + def->destination() + " SET " + incline_util::join(',', set_expr) + " WHERE " + incline_util::join(" AND ", cond); return incline_util::vectorize(sql); } vector<string> incline_driver_standalone::_merge_cond_of(const incline_def* def, const string& src_table) const { vector<string> cond; for (vector<pair<string, string> >::const_iterator mi = def->merge().begin(); mi != def->merge().end(); ++mi) { string src_col, cmp_col; if (incline_def::table_of_column(mi->first) == src_table) { src_col = mi->first; cmp_col = mi->second; } else if (incline_def::table_of_column(mi->second) == src_table) { src_col = mi->second; cmp_col = mi->first; } else { // do not know how to handle multiple dependent tables; sorry assert(0); } assert(def->columns().find(cmp_col) != def->columns().end()); cond.push_back(def->destination() + '.' + def->columns().find(cmp_col)->second + "=NEW." + src_col.substr(src_table.size() + 1)); } return cond; } string incline_driver_standalone::_build_insert_from_def(const incline_def *def, const string& dest_table, const string& src_table, action_t action, const vector<string>* _cond, const map<string, string>* extra_columns) { vector<string> cond; if (_cond != NULL) { incline_util::push_back(cond, *_cond); } string sql; bool use_update = action == act_update && ! incline_dbms::factory_->has_replace_into(); if (! use_update) { // INSERT or REPLACE vector<string> src_cols; for (map<string, string>::const_iterator ci = def->columns().begin(); ci != def->columns().end(); ++ci) { src_cols.push_back(incline_def::table_of_column(ci->first) == src_table ? "NEW" + ci->first.substr(src_table.size()) : ci->first); } sql = (action == act_insert ? "INSERT INTO " : "REPLACE INTO ") + dest_table + " (" + incline_util::join(',', incline_util::filter("%2", def->columns())); if (extra_columns != NULL) { sql += "," + incline_util::join(',', incline_util::filter("%1", *extra_columns)); } sql += ") SELECT " + incline_util::join(',', src_cols); } else { // UPDATE vector<string> src_cols; for (map<string, string>::const_iterator ci = def->npk_columns().begin(); ci != def->npk_columns().end(); ++ci) { src_cols.push_back(incline_def::table_of_column(ci->first) == src_table ? "NEW" + ci->first.substr(src_table.size()) : ci->first); } sql = "UPDATE " + dest_table + " SET (" + incline_util::join(',', incline_util::filter("%2", def->npk_columns())); if (extra_columns != NULL) { sql += "," + incline_util::join(',', incline_util::filter("%1", *extra_columns)); } sql += ")=(" + incline_util::join(',', src_cols); for (map<string, string>::const_iterator ci = def->pk_columns().begin(); ci != def->pk_columns().end(); ++ci) { cond.push_back(ci->second + "=" + (incline_def::table_of_column(ci->first) == src_table ? "NEW" + ci->first.substr(src_table.size()) : ci->first)); } } if (extra_columns != NULL) { sql += "," + incline_util::join(',', incline_util::filter("%2", *extra_columns)); } if (use_update) { sql += ") "; } if (def->source().size() > 1) { vector<string> join_tables; for (vector<string>::const_iterator si = def->source().begin(); si != def->source().end(); ++si) { if (*si != src_table) { join_tables.push_back(*si); } } sql += " FROM " + incline_util::join(",", join_tables); incline_util::push_back(cond, def->build_merge_cond(src_table, "NEW")); } if (! cond.empty()) { sql += " WHERE " + incline_util::join(" AND ", cond); } return sql; } <commit_msg>bugfix: deletes too many rows when merging multiple tables and if the column only shows up in the merge def. (but not in pk_columns)<commit_after>#include "incline_mgr.h" #include "incline_dbms.h" #include "incline_driver_standalone.h" #include "incline_util.h" using namespace std; vector<string> incline_driver_standalone::insert_trigger_of(const string& src_table) const { vector<string> body; for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_master_of(src_table)) { incline_util::push_back(body, _build_insert_from_def(def, src_table, act_insert)); } } return mgr_->build_trigger_stmt(src_table, "INSERT", body); } vector<string> incline_driver_standalone::update_trigger_of(const string& src_table) const { vector<string> body; for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_dependent_of(src_table)) { if (def->is_master_of(src_table)) { if (! def->npk_columns().empty()) { incline_util::push_back(body, _build_insert_from_def(def, src_table, act_update)); } } else { incline_util::push_back(body, _build_update_merge_from_def(def, src_table)); } } } return mgr_->build_trigger_stmt(src_table, "UPDATE", body); } vector<string> incline_driver_standalone::delete_trigger_of(const string& src_table) const { vector<string> body; for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_master_of(src_table)) { incline_util::push_back(body, _build_delete_from_def(def, src_table)); } } return mgr_->build_trigger_stmt(src_table, "DELETE", body); } vector<string> incline_driver_standalone::_build_insert_from_def(const incline_def* def, const string& src_table, action_t action, const vector<string>* _cond) const { string sql = _build_insert_from_def(def, def->destination(), src_table, action, _cond, NULL); return incline_util::vectorize(sql); } vector<string> incline_driver_standalone::_build_delete_from_def(const incline_def* def, const string& src_table, const vector<string>& _cond) const { vector<string> cond(_cond); for (map<string, string>::const_iterator pi = def->pk_columns().begin(); pi != def->pk_columns().end(); ++pi) { if (incline_def::table_of_column(pi->first) == src_table) { cond.push_back(pi->second + "=OLD." + pi->first.substr(src_table.size() + 1)); } } for (vector<pair<string, string> >::const_iterator mi = def->merge().begin(); mi != def->merge().end(); ++mi) { string old_col, alias_col; if (incline_def::table_of_column(mi->first) == src_table) { old_col = mi->first; alias_col = mi->second; } else if (incline_def::table_of_column(mi->second) == src_table) { old_col = mi->second; alias_col = mi->first; } if (! old_col.empty() && alias_col != src_table) { map<string, string>::const_iterator ci = def->pk_columns().find(alias_col); if (ci != def->pk_columns().end()) { cond.push_back(ci->second + "=OLD." + old_col.substr(src_table.size() + 1)); } else { // either column used in relation definition should exist in pk_columns, // at least for now... assert(def->pk_columns().find(old_col) != def->pk_columns().end()); } } } string sql = "DELETE FROM " + def->destination() + " WHERE " + incline_util::join(" AND ", cond); return incline_util::vectorize(sql); } vector<string> incline_driver_standalone::_build_update_merge_from_def(const incline_def* def, const string& src_table, const vector<string>& _cond) const { vector<string> set_expr, cond(_cond); for (map<string, string>::const_iterator ci = def->columns().begin(); ci != def->columns().end(); ++ci) { if (incline_def::table_of_column(ci->first) == src_table) { set_expr.push_back(ci->second + "=NEW." + ci->first.substr(src_table.size() + 1)); } } incline_util::push_back(cond, _merge_cond_of(def, src_table)); string sql = "UPDATE " + def->destination() + " SET " + incline_util::join(',', set_expr) + " WHERE " + incline_util::join(" AND ", cond); return incline_util::vectorize(sql); } vector<string> incline_driver_standalone::_merge_cond_of(const incline_def* def, const string& src_table) const { vector<string> cond; for (vector<pair<string, string> >::const_iterator mi = def->merge().begin(); mi != def->merge().end(); ++mi) { string src_col, cmp_col; if (incline_def::table_of_column(mi->first) == src_table) { src_col = mi->first; cmp_col = mi->second; } else if (incline_def::table_of_column(mi->second) == src_table) { src_col = mi->second; cmp_col = mi->first; } else { // do not know how to handle multiple dependent tables; sorry assert(0); } assert(def->columns().find(cmp_col) != def->columns().end()); cond.push_back(def->destination() + '.' + def->columns().find(cmp_col)->second + "=NEW." + src_col.substr(src_table.size() + 1)); } return cond; } string incline_driver_standalone::_build_insert_from_def(const incline_def *def, const string& dest_table, const string& src_table, action_t action, const vector<string>* _cond, const map<string, string>* extra_columns) { vector<string> cond; if (_cond != NULL) { incline_util::push_back(cond, *_cond); } string sql; bool use_update = action == act_update && ! incline_dbms::factory_->has_replace_into(); if (! use_update) { // INSERT or REPLACE vector<string> src_cols; for (map<string, string>::const_iterator ci = def->columns().begin(); ci != def->columns().end(); ++ci) { src_cols.push_back(incline_def::table_of_column(ci->first) == src_table ? "NEW" + ci->first.substr(src_table.size()) : ci->first); } sql = (action == act_insert ? "INSERT INTO " : "REPLACE INTO ") + dest_table + " (" + incline_util::join(',', incline_util::filter("%2", def->columns())); if (extra_columns != NULL) { sql += "," + incline_util::join(',', incline_util::filter("%1", *extra_columns)); } sql += ") SELECT " + incline_util::join(',', src_cols); } else { // UPDATE vector<string> src_cols; for (map<string, string>::const_iterator ci = def->npk_columns().begin(); ci != def->npk_columns().end(); ++ci) { src_cols.push_back(incline_def::table_of_column(ci->first) == src_table ? "NEW" + ci->first.substr(src_table.size()) : ci->first); } sql = "UPDATE " + dest_table + " SET (" + incline_util::join(',', incline_util::filter("%2", def->npk_columns())); if (extra_columns != NULL) { sql += "," + incline_util::join(',', incline_util::filter("%1", *extra_columns)); } sql += ")=(" + incline_util::join(',', src_cols); for (map<string, string>::const_iterator ci = def->pk_columns().begin(); ci != def->pk_columns().end(); ++ci) { cond.push_back(ci->second + "=" + (incline_def::table_of_column(ci->first) == src_table ? "NEW" + ci->first.substr(src_table.size()) : ci->first)); } } if (extra_columns != NULL) { sql += "," + incline_util::join(',', incline_util::filter("%2", *extra_columns)); } if (use_update) { sql += ") "; } if (def->source().size() > 1) { vector<string> join_tables; for (vector<string>::const_iterator si = def->source().begin(); si != def->source().end(); ++si) { if (*si != src_table) { join_tables.push_back(*si); } } sql += " FROM " + incline_util::join(",", join_tables); incline_util::push_back(cond, def->build_merge_cond(src_table, "NEW")); } if (! cond.empty()) { sql += " WHERE " + incline_util::join(" AND ", cond); } return sql; } <|endoftext|>
<commit_before>#include "incline_mgr.h" #include "incline_dbms.h" #include "incline_driver_standalone.h" #include "incline_util.h" using namespace std; void incline_driver_standalone::insert_trigger_of(trigger_body& body, const string& src_table) const { for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_master_of(src_table)) { _build_insert_from_def(body, def, src_table, act_insert); } } } void incline_driver_standalone::update_trigger_of(trigger_body& body, const string& src_table) const { for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_dependent_of(src_table)) { if (def->is_master_of(src_table)) { if (! def->npk_columns().empty()) { _build_insert_from_def(body, def, src_table, act_update); } } else { _build_update_merge_from_def(body, def, src_table); } } } } void incline_driver_standalone::delete_trigger_of(trigger_body& body, const string& src_table) const { for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_master_of(src_table)) { _build_delete_from_def(body, def, src_table); } } } void incline_driver_standalone::_build_insert_from_def(trigger_body& body, const incline_def* def, const string& src_table, action_t action, const vector<string>* _cond) const { _build_insert_from_def(body, def, def->destination(), src_table, action, _cond, NULL); } void incline_driver_standalone::_build_delete_from_def(trigger_body& body, const incline_def* def, const string& src_table, const vector<string>& _cond) const { vector<string> cond(_cond); string sql; bool use_join = false; for (vector<pair<string, string> >::const_iterator mi = def->merge().begin(); mi != def->merge().end(); ++mi) { if (def->pk_columns().find(mi->first) == def->pk_columns().end() && def->pk_columns().find(mi->second) == def->pk_columns().end()) { use_join = true; break; } } for (map<string, string>::const_iterator pi = def->pk_columns().begin(); pi != def->pk_columns().end(); ++pi) { if (incline_def::table_of_column(pi->first) == src_table) { cond.push_back(def->destination() + '.' + pi->second + "=OLD." + pi->first.substr(src_table.size() + 1)); } } if (use_join) { vector<string> using_list; for (vector<string>::const_iterator si = def->source().begin(); si != def->source().end(); ++si) { if (*si != src_table && def->is_master_of(*si)) { using_list.push_back(*si); for (map<string, string>::const_iterator pi = def->pk_columns().begin(); pi != def->pk_columns().end(); ++pi) { if (incline_def::table_of_column(pi->first) == *si) { cond.push_back(def->destination() + '.' + pi->second + '=' + pi->first); } } } } incline_util::push_back(cond, def->build_merge_cond(src_table, "OLD", true)); sql = incline_dbms::factory_->delete_using(def->destination(), using_list) + " WHERE " + incline_util::join(" AND ", cond); } else { for (vector<pair<string, string> >::const_iterator mi = def->merge().begin(); mi != def->merge().end(); ++mi) { string old_col, alias_col; if (incline_def::table_of_column(mi->first) == src_table) { old_col = mi->first; alias_col = mi->second; } else if (incline_def::table_of_column(mi->second) == src_table) { old_col = mi->second; alias_col = mi->first; } if (! old_col.empty() && def->pk_columns().find(old_col) == def->pk_columns().end()) { map<string, string>::const_iterator ci = def->pk_columns().find(alias_col); assert(ci != def->pk_columns().end()); cond.push_back(ci->second + "=OLD." + old_col.substr(src_table.size() + 1)); } } sql = "DELETE FROM " + def->destination() + " WHERE " + incline_util::join(" AND ", cond); } body.stmt.push_back(sql); } void incline_driver_standalone::_build_update_merge_from_def(trigger_body& body, const incline_def* def, const string& src_table, const vector<string>& _cond) const { vector<string> set_expr, cond(_cond); for (map<string, string>::const_iterator ci = def->columns().begin(); ci != def->columns().end(); ++ci) { if (incline_def::table_of_column(ci->first) == src_table) { set_expr.push_back(ci->second + "=NEW." + ci->first.substr(src_table.size() + 1)); } } incline_util::push_back(cond, _merge_cond_of(def, src_table)); string sql = "UPDATE " + def->destination() + " SET " + incline_util::join(',', set_expr) + " WHERE " + incline_util::join(" AND ", cond); body.stmt.push_back(sql); } vector<string> incline_driver_standalone::_merge_cond_of(const incline_def* def, const string& src_table) const { vector<string> cond; for (vector<pair<string, string> >::const_iterator mi = def->merge().begin(); mi != def->merge().end(); ++mi) { string src_col, cmp_col; if (incline_def::table_of_column(mi->first) == src_table) { src_col = mi->first; cmp_col = mi->second; } else if (incline_def::table_of_column(mi->second) == src_table) { src_col = mi->second; cmp_col = mi->first; } else { // do not know how to handle multiple dependent tables; sorry assert(0); } assert(def->columns().find(cmp_col) != def->columns().end()); cond.push_back(def->destination() + '.' + def->columns().find(cmp_col)->second + "=NEW." + src_col.substr(src_table.size() + 1)); } return cond; } void incline_driver_standalone::_build_insert_from_def(trigger_body& body, const incline_def *def, const string& dest_table, const string& src_table, action_t action, const vector<string>* _cond, const map<string, string>* extra_columns) { if (action == act_update && def->npk_columns().empty()) { // nothing to do (pks should not be altered in an UPDATE statement) return; } vector<string> cond; if (_cond != NULL) { incline_util::push_back(cond, *_cond); } if (action == act_update && def->source().size() == 1) { // use: UPDATE ... WHERE ... string sql = "UPDATE " + dest_table + " SET " + incline_util::join(",", incline_util::filter("%2=%1", incline_util::filter(incline_util::rewrite_prefix(def->source()[0] + '.', "NEW."), NULL, def->npk_columns()))) + " WHERE " + incline_util::join(" AND ", incline_util::filter("%2=%1", incline_util::filter(incline_util::rewrite_prefix(def->source()[0] + '.', "NEW."), NULL, def->pk_columns()))); body.stmt.push_back(sql); return; } // use: SELECT (with for UPDATE if necessary) string query; bool use_update = action == act_update && ! incline_dbms::factory_->has_replace_into(); { // build query vector<string> src_cols; for (map<string, string>::const_iterator ci = def->columns().begin(); ci != def->columns().end(); ++ci) { src_cols.push_back(incline_util::rewrite_prefix(src_table + '.', "NEW.") (ci->first)); if (use_update) { src_cols.back() += " AS _" + ci->second; } } query = "SELECT " + incline_util::join(',', src_cols); if (extra_columns != NULL) { query += "," + incline_util::join(',', incline_util::filter("%2", *extra_columns)); } if (def->source().size() > 1) { vector<string> join_tables; for (vector<string>::const_iterator si = def->source().begin(); si != def->source().end(); ++si) { if (*si != src_table) { join_tables.push_back(*si); } } query += " FROM " + incline_util::join(",", join_tables); incline_util::push_back(cond, def->build_merge_cond(src_table, "NEW")); } if (! cond.empty()) { query += " WHERE " + incline_util::join(" AND ", cond); } if (def->source().size() > 1) { query += " FOR UPDATE"; } } if (! use_update) { // mysql string sql = (action == act_insert ? "INSERT INTO " : "REPLACE INTO ") + dest_table + " (" + incline_util::join(',', incline_util::filter("%2", def->columns())); if (extra_columns != NULL) { sql += "," + incline_util::join(',', incline_util::filter("%1", *extra_columns)); } sql += ") " + query; body.stmt.push_back(sql); } else { // postgresql string sql = "UPDATE " + dest_table + " SET (" + incline_util::join(',', incline_util::filter("%2", def->npk_columns())) + ")=(" + incline_util::join(',', incline_util::filter("srow._%2", def->npk_columns())) + ") WHERE " + incline_util::join(" AND ", incline_util::filter("%2=srow._%2", def->pk_columns())); body.var.push_back("srow RECORD"); body.stmt.push_back("FOR srow IN " + query + " LOOP\\"); body.stmt.push_back(sql); body.stmt.push_back("END LOOP"); } } <commit_msg>set extra_columns<commit_after>#include "incline_mgr.h" #include "incline_dbms.h" #include "incline_driver_standalone.h" #include "incline_util.h" using namespace std; void incline_driver_standalone::insert_trigger_of(trigger_body& body, const string& src_table) const { for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_master_of(src_table)) { _build_insert_from_def(body, def, src_table, act_insert); } } } void incline_driver_standalone::update_trigger_of(trigger_body& body, const string& src_table) const { for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_dependent_of(src_table)) { if (def->is_master_of(src_table)) { if (! def->npk_columns().empty()) { _build_insert_from_def(body, def, src_table, act_update); } } else { _build_update_merge_from_def(body, def, src_table); } } } } void incline_driver_standalone::delete_trigger_of(trigger_body& body, const string& src_table) const { for (vector<incline_def*>::const_iterator di = mgr_->defs().begin(); di != mgr_->defs().end(); ++di) { const incline_def* def = *di; if (def->is_master_of(src_table)) { _build_delete_from_def(body, def, src_table); } } } void incline_driver_standalone::_build_insert_from_def(trigger_body& body, const incline_def* def, const string& src_table, action_t action, const vector<string>* _cond) const { _build_insert_from_def(body, def, def->destination(), src_table, action, _cond, NULL); } void incline_driver_standalone::_build_delete_from_def(trigger_body& body, const incline_def* def, const string& src_table, const vector<string>& _cond) const { vector<string> cond(_cond); string sql; bool use_join = false; for (vector<pair<string, string> >::const_iterator mi = def->merge().begin(); mi != def->merge().end(); ++mi) { if (def->pk_columns().find(mi->first) == def->pk_columns().end() && def->pk_columns().find(mi->second) == def->pk_columns().end()) { use_join = true; break; } } for (map<string, string>::const_iterator pi = def->pk_columns().begin(); pi != def->pk_columns().end(); ++pi) { if (incline_def::table_of_column(pi->first) == src_table) { cond.push_back(def->destination() + '.' + pi->second + "=OLD." + pi->first.substr(src_table.size() + 1)); } } if (use_join) { vector<string> using_list; for (vector<string>::const_iterator si = def->source().begin(); si != def->source().end(); ++si) { if (*si != src_table && def->is_master_of(*si)) { using_list.push_back(*si); for (map<string, string>::const_iterator pi = def->pk_columns().begin(); pi != def->pk_columns().end(); ++pi) { if (incline_def::table_of_column(pi->first) == *si) { cond.push_back(def->destination() + '.' + pi->second + '=' + pi->first); } } } } incline_util::push_back(cond, def->build_merge_cond(src_table, "OLD", true)); sql = incline_dbms::factory_->delete_using(def->destination(), using_list) + " WHERE " + incline_util::join(" AND ", cond); } else { for (vector<pair<string, string> >::const_iterator mi = def->merge().begin(); mi != def->merge().end(); ++mi) { string old_col, alias_col; if (incline_def::table_of_column(mi->first) == src_table) { old_col = mi->first; alias_col = mi->second; } else if (incline_def::table_of_column(mi->second) == src_table) { old_col = mi->second; alias_col = mi->first; } if (! old_col.empty() && def->pk_columns().find(old_col) == def->pk_columns().end()) { map<string, string>::const_iterator ci = def->pk_columns().find(alias_col); assert(ci != def->pk_columns().end()); cond.push_back(ci->second + "=OLD." + old_col.substr(src_table.size() + 1)); } } sql = "DELETE FROM " + def->destination() + " WHERE " + incline_util::join(" AND ", cond); } body.stmt.push_back(sql); } void incline_driver_standalone::_build_update_merge_from_def(trigger_body& body, const incline_def* def, const string& src_table, const vector<string>& _cond) const { vector<string> set_expr, cond(_cond); for (map<string, string>::const_iterator ci = def->columns().begin(); ci != def->columns().end(); ++ci) { if (incline_def::table_of_column(ci->first) == src_table) { set_expr.push_back(ci->second + "=NEW." + ci->first.substr(src_table.size() + 1)); } } incline_util::push_back(cond, _merge_cond_of(def, src_table)); string sql = "UPDATE " + def->destination() + " SET " + incline_util::join(',', set_expr) + " WHERE " + incline_util::join(" AND ", cond); body.stmt.push_back(sql); } vector<string> incline_driver_standalone::_merge_cond_of(const incline_def* def, const string& src_table) const { vector<string> cond; for (vector<pair<string, string> >::const_iterator mi = def->merge().begin(); mi != def->merge().end(); ++mi) { string src_col, cmp_col; if (incline_def::table_of_column(mi->first) == src_table) { src_col = mi->first; cmp_col = mi->second; } else if (incline_def::table_of_column(mi->second) == src_table) { src_col = mi->second; cmp_col = mi->first; } else { // do not know how to handle multiple dependent tables; sorry assert(0); } assert(def->columns().find(cmp_col) != def->columns().end()); cond.push_back(def->destination() + '.' + def->columns().find(cmp_col)->second + "=NEW." + src_col.substr(src_table.size() + 1)); } return cond; } void incline_driver_standalone::_build_insert_from_def(trigger_body& body, const incline_def *def, const string& dest_table, const string& src_table, action_t action, const vector<string>* _cond, const map<string, string>* extra_columns) { if (action == act_update && def->npk_columns().empty()) { // nothing to do (pks should not be altered in an UPDATE statement) return; } vector<string> cond; if (_cond != NULL) { incline_util::push_back(cond, *_cond); } if (action == act_update && def->source().size() == 1) { // use: UPDATE ... WHERE ... string sql = "UPDATE " + dest_table + " SET " + incline_util::join(",", incline_util::filter("%2=%1", incline_util::filter(incline_util::rewrite_prefix(def->source()[0] + '.', "NEW."), NULL, def->npk_columns()))) + " WHERE " + incline_util::join(" AND ", incline_util::filter("%2=%1", incline_util::filter(incline_util::rewrite_prefix(def->source()[0] + '.', "NEW."), NULL, def->pk_columns()))); body.stmt.push_back(sql); return; } // use: SELECT (with for UPDATE if necessary) string query; bool use_update = action == act_update && ! incline_dbms::factory_->has_replace_into(); { // build query vector<string> src_cols; for (map<string, string>::const_iterator ci = def->columns().begin(); ci != def->columns().end(); ++ci) { src_cols.push_back(incline_util::rewrite_prefix(src_table + '.', "NEW.") (ci->first)); if (use_update) { src_cols.back() += " AS _" + ci->second; } } query = "SELECT " + incline_util::join(',', src_cols); if (! use_update && extra_columns != NULL) { query += "," + incline_util::join(',', incline_util::filter("%2", *extra_columns)); } if (def->source().size() > 1) { vector<string> join_tables; for (vector<string>::const_iterator si = def->source().begin(); si != def->source().end(); ++si) { if (*si != src_table) { join_tables.push_back(*si); } } query += " FROM " + incline_util::join(",", join_tables); incline_util::push_back(cond, def->build_merge_cond(src_table, "NEW")); } if (! cond.empty()) { query += " WHERE " + incline_util::join(" AND ", cond); } if (def->source().size() > 1) { query += " FOR UPDATE"; } } if (! use_update) { // mysql string sql = (action == act_insert ? "INSERT INTO " : "REPLACE INTO ") + dest_table + " (" + incline_util::join(',', incline_util::filter("%2", def->columns())); if (extra_columns != NULL) { sql += "," + incline_util::join(',', incline_util::filter("%1", *extra_columns)); } sql += ") " + query; body.stmt.push_back(sql); } else { // postgresql string sql = "UPDATE " + dest_table + " SET " + incline_util::join(',', incline_util::filter("%2=srow._%2", def->npk_columns())); if (extra_columns != NULL) { sql += "," + incline_util::join(',', incline_util::filter("%1=%2", *extra_columns)); } sql += " WHERE " + incline_util::join(" AND ", incline_util::filter("%2=srow._%2", def->pk_columns())); body.var.push_back("srow RECORD"); body.stmt.push_back("FOR srow IN " + query + " LOOP\\"); body.stmt.push_back(sql); body.stmt.push_back("END LOOP"); } } <|endoftext|>
<commit_before>#pragma once /* libsoundbag Copyright (c) 2017 Togo Nishigaki This software released under MIT License http://opensource.org/licenses/mit-license.php */ #ifndef libsoundbag_threads_h #define libsoundbag_threads_h namespace soundbag { /* usage: { soundbag::try_lock<mutex> locker(_mutex); if( locker ){ ... } } */ template<class T> class try_lock { T& m_mutex; bool locked; public: try_lock( T& m ) : m_mutex(m) { locked = m_mutex.try_lock(); } virtual ~try_lock() { if( locked ){ m_mutex.unlock(); } } operator bool() const { return locked; } }; } #endif<commit_msg>Modify destructor of class try_lock (remove 'virtual' keyword)<commit_after>#pragma once /* libsoundbag Copyright (c) 2017 Togo Nishigaki This software released under MIT License http://opensource.org/licenses/mit-license.php */ #ifndef libsoundbag_threads_h #define libsoundbag_threads_h namespace soundbag { /* usage: { soundbag::try_lock<mutex> locker(_mutex); if( locker ){ ... } } */ template<class T> class try_lock { T& m_mutex; bool locked; public: try_lock( T& m ) : m_mutex(m) { locked = m_mutex.try_lock(); } ~try_lock() { if( locked ){ m_mutex.unlock(); } } operator bool() const { return locked; } }; } #endif<|endoftext|>
<commit_before>#ifndef CONTAINERS_SCOPED_HPP_ #define CONTAINERS_SCOPED_HPP_ #include <string.h> #include "errors.hpp" #include "containers/archive/archive.hpp" // Like boost::scoped_ptr only with release, init, no bool conversion, no boost headers! template <class T> class scoped_ptr_t { public: scoped_ptr_t() : ptr_(NULL) { } explicit scoped_ptr_t(T *p) : ptr_(p) { } ~scoped_ptr_t() { reset(); } // includes a sanity-check for first-time use. void init(T *value) { rassert(ptr_ == NULL); // This is like reset with an assert. T *tmp = ptr_; ptr_ = value; delete tmp; } void reset() { T *tmp = ptr_; ptr_ = NULL; delete tmp; } MUST_USE T *release() { T *tmp = ptr_; ptr_ = NULL; return tmp; } void swap(scoped_ptr_t& other) { T *tmp = ptr_; ptr_ = other.ptr_; other.ptr_ = tmp; } T *get() const { rassert(ptr_); return ptr_; } T *operator->() const { rassert(ptr_); return ptr_; } bool has() const { return ptr_ != NULL; } private: T *ptr_; DISABLE_COPYING(scoped_ptr_t); }; // Not really like boost::scoped_array. A fascist array. template <class T> class scoped_array_t { public: scoped_array_t() : ptr_(NULL), size_(0) { } explicit scoped_array_t(ssize_t n) : ptr_(NULL), size_(0) { init(n); } scoped_array_t(T *ptr, ssize_t size) : ptr_(NULL), size_(0) { init(ptr, size); } ~scoped_array_t() { reset(); } void init(ssize_t n) { rassert(ptr_ == NULL); rassert(n >= 0); ptr_ = new T[n]; size_ = n; } // The opposite of release. void init(T *ptr, ssize_t size) { rassert(ptr != NULL); rassert(ptr_ == NULL); rassert(size >= 0); ptr_ = ptr; size_ = size; } void reset() { T *tmp = ptr_; ptr_ = NULL; size_ = 0; delete[] tmp; } MUST_USE T *release(ssize_t *size_out) { *size_out = size_; T *tmp = ptr_; ptr_ = NULL; size_ = 0; return tmp; } void swap(scoped_array_t &other) { T *tmp = ptr_; ssize_t tmpsize = size_; ptr_ = other.ptr_; size_ = other.size_; other.ptr_ = tmp; other.size_ = tmpsize; } T& operator[](ssize_t i) const { rassert(ptr_); rassert(0 <= i && i < size_); return ptr_[i]; } T *data() const { rassert(ptr_); return ptr_; } ssize_t size() const { rassert(ptr_); return size_; } bool has() const { return ptr_ != NULL; } private: T *ptr_; ssize_t size_; DISABLE_COPYING(scoped_array_t); }; template <class T> write_message_t &operator<<(write_message_t &msg, const scoped_array_t<T> &a) { msg << a.size(); for (T *it = a.data(); it != a.data() + a.size(); ++it) { msg << *it; } return msg; } template <class T> MUST_USE archive_result_t deserialize(read_stream_t *s, scoped_array_t<T> *a) { archive_result_t res; int size; if ((res = deserialize(s, &size))) { return res; } a->reset(); a->init(size); for (T *it = a->data(); it != a->data() + a->size(); ++it) { if ((res = deserialize(s, it))) { return res; } } return res; } // For dumb structs that get malloc/free for allocation. template <class T> class scoped_malloc_t { public: scoped_malloc_t() : ptr_(NULL) { } explicit scoped_malloc_t(size_t n) : ptr_(reinterpret_cast<T *>(malloc(n))) { } scoped_malloc_t(const char *beg, const char *end) { rassert(beg <= end); size_t n = end - beg; ptr_ = reinterpret_cast<T *>(malloc(n)); memcpy(ptr_, beg, n); } ~scoped_malloc_t() { free(ptr_); } T *get() { return ptr_; } const T *get() const { return ptr_; } T *operator->() { return ptr_; } const T *operator->() const { return ptr_; } T& operator*() { return *ptr_; } void reset() { scoped_malloc_t tmp; swap(tmp); } void swap(scoped_malloc_t& other) { // NOLINT T *tmp = ptr_; ptr_ = other.ptr_; other.ptr_ = tmp; } template <class U> friend class scoped_malloc_t; template <class U> void reinterpret_swap(scoped_malloc_t<U>& other) { T *tmp = ptr_; ptr_ = reinterpret_cast<T *>(other.ptr_); other.ptr_ = reinterpret_cast<U *>(tmp); } bool has() const { return ptr_ != NULL; } private: T *ptr_; // DISABLE_COPYING scoped_malloc_t(const scoped_malloc_t&); void operator=(const scoped_malloc_t&); }; #endif // CONTAINERS_SCOPED_HPP_ <commit_msg>Made scoped_array_t serialization and deserialization functions be consistent with one another.<commit_after>#ifndef CONTAINERS_SCOPED_HPP_ #define CONTAINERS_SCOPED_HPP_ #include <string.h> #include "errors.hpp" #include "containers/archive/archive.hpp" // Like boost::scoped_ptr only with release, init, no bool conversion, no boost headers! template <class T> class scoped_ptr_t { public: scoped_ptr_t() : ptr_(NULL) { } explicit scoped_ptr_t(T *p) : ptr_(p) { } ~scoped_ptr_t() { reset(); } // includes a sanity-check for first-time use. void init(T *value) { rassert(ptr_ == NULL); // This is like reset with an assert. T *tmp = ptr_; ptr_ = value; delete tmp; } void reset() { T *tmp = ptr_; ptr_ = NULL; delete tmp; } MUST_USE T *release() { T *tmp = ptr_; ptr_ = NULL; return tmp; } void swap(scoped_ptr_t& other) { T *tmp = ptr_; ptr_ = other.ptr_; other.ptr_ = tmp; } T *get() const { rassert(ptr_); return ptr_; } T *operator->() const { rassert(ptr_); return ptr_; } bool has() const { return ptr_ != NULL; } private: T *ptr_; DISABLE_COPYING(scoped_ptr_t); }; // Not really like boost::scoped_array. A fascist array. template <class T> class scoped_array_t { public: scoped_array_t() : ptr_(NULL), size_(0) { } explicit scoped_array_t(ssize_t n) : ptr_(NULL), size_(0) { init(n); } scoped_array_t(T *ptr, ssize_t size) : ptr_(NULL), size_(0) { init(ptr, size); } ~scoped_array_t() { reset(); } void init(ssize_t n) { rassert(ptr_ == NULL); rassert(n >= 0); ptr_ = new T[n]; size_ = n; } // The opposite of release. void init(T *ptr, ssize_t size) { rassert(ptr != NULL); rassert(ptr_ == NULL); rassert(size >= 0); ptr_ = ptr; size_ = size; } void reset() { T *tmp = ptr_; ptr_ = NULL; size_ = 0; delete[] tmp; } MUST_USE T *release(ssize_t *size_out) { *size_out = size_; T *tmp = ptr_; ptr_ = NULL; size_ = 0; return tmp; } void swap(scoped_array_t &other) { T *tmp = ptr_; ssize_t tmpsize = size_; ptr_ = other.ptr_; size_ = other.size_; other.ptr_ = tmp; other.size_ = tmpsize; } T& operator[](ssize_t i) const { rassert(ptr_); rassert(0 <= i && i < size_); return ptr_[i]; } T *data() const { rassert(ptr_); return ptr_; } ssize_t size() const { rassert(ptr_); return size_; } bool has() const { return ptr_ != NULL; } private: T *ptr_; ssize_t size_; DISABLE_COPYING(scoped_array_t); }; template <class T> write_message_t &operator<<(write_message_t &msg, const scoped_array_t<T> &a) { int64_t size = a.size(); msg << size; for (T *it = a.data(); it != a.data() + a.size(); ++it) { msg << *it; } return msg; } template <class T> MUST_USE archive_result_t deserialize(read_stream_t *s, scoped_array_t<T> *a) { archive_result_t res; int64_t size; if ((res = deserialize(s, &size))) { return res; } a->reset(); a->init(size); for (T *it = a->data(); it != a->data() + a->size(); ++it) { if ((res = deserialize(s, it))) { return res; } } return res; } // For dumb structs that get malloc/free for allocation. template <class T> class scoped_malloc_t { public: scoped_malloc_t() : ptr_(NULL) { } explicit scoped_malloc_t(size_t n) : ptr_(reinterpret_cast<T *>(malloc(n))) { } scoped_malloc_t(const char *beg, const char *end) { rassert(beg <= end); size_t n = end - beg; ptr_ = reinterpret_cast<T *>(malloc(n)); memcpy(ptr_, beg, n); } ~scoped_malloc_t() { free(ptr_); } T *get() { return ptr_; } const T *get() const { return ptr_; } T *operator->() { return ptr_; } const T *operator->() const { return ptr_; } T& operator*() { return *ptr_; } void reset() { scoped_malloc_t tmp; swap(tmp); } void swap(scoped_malloc_t& other) { // NOLINT T *tmp = ptr_; ptr_ = other.ptr_; other.ptr_ = tmp; } template <class U> friend class scoped_malloc_t; template <class U> void reinterpret_swap(scoped_malloc_t<U>& other) { T *tmp = ptr_; ptr_ = reinterpret_cast<T *>(other.ptr_); other.ptr_ = reinterpret_cast<U *>(tmp); } bool has() const { return ptr_ != NULL; } private: T *ptr_; // DISABLE_COPYING scoped_malloc_t(const scoped_malloc_t&); void operator=(const scoped_malloc_t&); }; #endif // CONTAINERS_SCOPED_HPP_ <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <cmath> #include <cstring> #include <vector> #include "Page.h" using std::cout; using std::cerr; using std::endl; using std::string; using std::stoi; using std::ifstream; using std::ofstream; bool checkParameters(int argc, char* argv[],ifstream& programListIn, ifstream& programTraceIn, int& pageSize, string& replacementAlgorithm, string& pagingMethod); void replacePage(int requestingProgram, int requestedPage); const string REPLACEMENT_ALGORITHMS[3] = {"lru", "clock", "fifo"}, PAGING_METHODS[2] = {"d", "p"}; const int NUM_REPLACEMENT_ALGORITHMS = 3, NUM_PAGING_METHODS = 2, AVAILABLE_FRAMES = 512, NUM_PROGRAMS = 10; //Global variables unsigned long long timestamp = 0; int pageSize, pagesPerProgram, numFrames, pageFaults = 0, clockIndex = 0; int programSizes[NUM_PROGRAMS]; string replacementAlgorithm, pagingMethod; Page** mainPageTable; Page** pageTables[NUM_PROGRAMS]; int main(int argc, char* argv[]) { std::ifstream programListIn, programTraceIn; int x, tmp, requestingProgram, requestedPage, pagesInMainMemory = 0; if(!checkParameters(argc, argv, programListIn, programTraceIn, pageSize, replacementAlgorithm, pagingMethod)) { //Error condition return -1; } //We're ready to roll numFrames = AVAILABLE_FRAMES / pageSize; //Main page table is an array of pointers to pages mainPageTable = new Page*[numFrames]; for(int i = 0; i < numFrames; i++) { mainPageTable[i] = NULL; } for(int i = 0; i < NUM_PROGRAMS; i++) { //Skip first part programListIn >> x; //Grab program size programListIn >> x; //Program i needs size/pageSize pages programSizes[i] = std::ceil(static_cast<double>(x) / pageSize); //Page table contains as many entries as pages needed pageTables[i] = new Page*[programSizes[i]]; //Set each element to NULL for(int j = 0; j < programSizes[i]; j++) { pageTables[i][j] = NULL; } //Time to pre-load each program's pages pagesPerProgram = numFrames / NUM_PROGRAMS; //If program i needs fewer than pagesPerProgram, only loop that many times x = programSizes[i] < pagesPerProgram ? programSizes[i] : pagesPerProgram; for (int j = 0; j < x; j++) { tmp = i * pagesPerProgram + j; mainPageTable[tmp] = new Page(i, j, timestamp); mainPageTable[tmp]->setUseBit(true); pagesInMainMemory++; pageTables[i][j] = mainPageTable[i * pagesPerProgram + j]; timestamp++; } } //Start reading in the program trace while(!programTraceIn.eof()) { programTraceIn >> requestingProgram; programTraceIn >> requestedPage; //Purposeful integer division, get floor of page requestedPage /= pageSize; //Page isn't resident if(pageTables[requestingProgram][requestedPage] == NULL) { pageFaults++; //There's space in main memory if(pagesInMainMemory != numFrames) { //Simply put the page at the end of the main table mainPageTable[pagesInMainMemory] = new Page(requestingProgram, requestedPage, timestamp); mainPageTable[pagesInMainMemory]->setUseBit(true); //Set the pointer pageTables[requestingProgram][requestedPage] = mainPageTable[pagesInMainMemory-1]; timestamp++; pagesInMainMemory++; } else { //Run a replacement algorithm replacePage(requestingProgram, requestedPage); //If we're using prepaging and requestedPage isn't the last logical page if(pagingMethod == "p" && requestedPage+1 < programSizes[requestingProgram]) { //If next page isn't resident if(pageTables[requestingProgram][requestedPage+1] == NULL) { replacePage(requestingProgram, requestedPage + 1); } else { //If using lru, update timestamp if(replacementAlgorithm == "lru") { pageTables[requestingProgram][requestedPage+1]->setTimestamp(timestamp); timestamp++; } else if(replacementAlgorithm == "clock") { pageTables[requestingProgram][requestedPage+1]->setUseBit(true); } } } } } else { //Page is resident //If using lru, update timestamp if(replacementAlgorithm == "lru") { pageTables[requestingProgram][requestedPage]->setTimestamp(timestamp); timestamp++; } else if(replacementAlgorithm == "clock") { pageTables[requestingProgram][requestedPage]->setUseBit(true); } } } //Close filestreams and delete data programListIn.close(); programTraceIn.close(); for(int i = 0; i < NUM_PROGRAMS; i++) { delete[] pageTables[i]; } delete[] mainPageTable; cout << "There were " << pageFaults << " page faults" << endl; return 0; } bool checkParameters(int argc, char* argv[], ifstream& programListIn, ifstream& programTraceIn, int& pageSize, string& replacementAlgorithm, string& pagingMethod) { bool pageSizeGood = false, replacementAlgorithmGood = false, pagingMethodGood = false; //Valid number of arguments, but some may not make sense if(argc == 6) { //Check to see if programList exists string filename = argv[1]; programListIn.open(filename + ".txt"); if(programListIn) { //File1 exists //Check to see if file2 exists filename = argv[2]; programTraceIn.open(filename + ".txt"); if(programTraceIn) { //File2 exists try { pageSize = std::stoi(argv[3]); //Page Size is numeric, but is it 1,2,4,8,16? for(int i = 0; i < 5; i++) { if(pageSize == std::pow(2, i)) { //It is pageSizeGood = true; break; } } if(pageSizeGood) { //Page size is good //Check replacement algorithm replacementAlgorithm = argv[4]; for(int i = 0; i < NUM_REPLACEMENT_ALGORITHMS; i++) { if(replacementAlgorithm == REPLACEMENT_ALGORITHMS[i]) { //Replacement algorithm is valid replacementAlgorithmGood = true; break; } } if(replacementAlgorithmGood) { //Replacement algorithm is valid //Check paging method pagingMethod = argv[5]; for(int i = 0; i < NUM_PAGING_METHODS; i++) { if(pagingMethod == PAGING_METHODS[i]) { pagingMethodGood = true; break; } } if(pagingMethodGood) { //Paging Method is valid //All Options are valid return true; } else { //Paging Method is invalid cerr << "Error: Paging Method " << pagingMethod << " is invalid." << endl; } } else { //It's not cerr << "Error: Page Replacement Algorithm " << replacementAlgorithm << " is invalid." << endl; } } else { //Page size isn't good cerr << "Error: " << pageSize << " is not a power of two." << endl; } } catch(std::invalid_argument e) { //Third argument is not an integer cerr << "Error: " << pageSize << " is not a numeric type." << endl; } } else { //It doesn't cerr << "Error: File " << argv[2] << ".txt does not exist. Please provide a valid filename" << endl; } } else { //It doesn't cerr << "Error: File " << argv[1] << ".txt does not exist. Please provide a valid filename" << endl; } } else { //Invalid number of parameters cerr << "Error: Invalid number of parameters provided. Please provide exactly 5 arguments." << endl; } cerr << endl; cerr << "Usage " << argv[0] << " programListFile programTraceFile numPages replacementAlgorithm pagingMethod" << endl; cerr << endl; cerr << "programListFile: The file containing the program list" << endl; cerr << "programTraceFile: The file containing the program trace" << endl; cerr << "numPages: The number of pages. Must be in the set {1,2,4,8,16}" << endl; cerr << "replacementAlgorithm: The replacement algorithm to use. Must be in the set {lru, fifo, clock}" << endl; cerr << "pagingMethod: The paging method to use. Must be in the set {p(Prepaging), d(Demand Paging)}" << endl; return false; } void replacePage(int requestingProgram, int requestedPage) { //LRU and FIFO replace pages the same way. The only difference is in how they update timestamps if(replacementAlgorithm == "lru" || replacementAlgorithm == "fifo") { int lruIndex = 0; //Find index of page with oldest timestamp for(int i = 0; i < numFrames; i++) { if(mainPageTable[i]->getTimestamp() < mainPageTable[lruIndex]->getTimestamp()) { lruIndex = i; } } //Replace page at index lruIndex Page p = *mainPageTable[lruIndex]; //Page p is no longer resident pageTables[p.getOwnerProgram()][p.getLogicalPageNum()] = NULL; delete mainPageTable[lruIndex]; mainPageTable[lruIndex] = new Page(requestingProgram, requestedPage, timestamp); pageTables[requestingProgram][requestedPage] = mainPageTable[lruIndex]; timestamp++; } else if(replacementAlgorithm == "clock") { while(mainPageTable[clockIndex]->getUseBit()) { //Clear the bit mainPageTable[clockIndex]->setUseBit(false); clockIndex++; clockIndex %= numFrames; } //Replace page at index clockIndex Page p = *mainPageTable[clockIndex]; //Page p is no longer resident pageTables[p.getOwnerProgram()][p.getLogicalPageNum()] = NULL; delete mainPageTable[clockIndex]; mainPageTable[clockIndex] = new Page(requestingProgram, requestedPage, timestamp); mainPageTable[clockIndex]->setUseBit(true); pageTables[requestingProgram][requestedPage] = mainPageTable[clockIndex]; timestamp++; } }<commit_msg>Misc. Changes<commit_after>#include <iostream> #include <fstream> #include <cmath> #include <cstring> #include <vector> #include "Page.h" using std::cout; using std::cerr; using std::endl; using std::string; using std::stoi; using std::ifstream; using std::ofstream; bool checkParameters(int argc, char* argv[],ifstream& programListIn, ifstream& programTraceIn, int& pageSize, string& replacementAlgorithm, string& pagingMethod); void replacePage(int requestingProgram, int requestedPage); int getIndexOfOldestPage(); const string REPLACEMENT_ALGORITHMS[3] = {"lru", "clock", "fifo"}, PAGING_METHODS[2] = {"d", "p"}; const int NUM_REPLACEMENT_ALGORITHMS = 3, NUM_PAGING_METHODS = 2, AVAILABLE_FRAMES = 512, NUM_PROGRAMS = 10; //Global variables unsigned long long timestamp = 0; int pageSize, pagesPerProgram, numFrames, pageFaults = 0, clockIndex = 0; int programSizes[NUM_PROGRAMS]; string replacementAlgorithm, pagingMethod; Page** mainPageTable; Page** pageTables[NUM_PROGRAMS]; int main(int argc, char* argv[]) { std::ifstream programListIn, programTraceIn; int x, tmp, requestingProgram, requestedPage, pagesInMainMemory = 0; if(!checkParameters(argc, argv, programListIn, programTraceIn, pageSize, replacementAlgorithm, pagingMethod)) { //Error condition return -1; } //We're ready to roll numFrames = AVAILABLE_FRAMES / pageSize; //Main page table is an array of pointers to pages mainPageTable = new Page*[numFrames]; for(int i = 0; i < numFrames; i++) { mainPageTable[i] = NULL; } for(int i = 0; i < NUM_PROGRAMS; i++) { //Skip first part programListIn >> x; //Grab program size programListIn >> x; //Program i needs size/pageSize pages programSizes[i] = std::ceil(static_cast<double>(x) / pageSize); //Page table contains as many entries as pages needed pageTables[i] = new Page*[programSizes[i]]; //Set each element to NULL for(int j = 0; j < programSizes[i]; j++) { pageTables[i][j] = NULL; } //Time to pre-load each program's pages pagesPerProgram = numFrames / NUM_PROGRAMS; //If program i needs fewer than pagesPerProgram, only loop that many times x = programSizes[i] < pagesPerProgram ? programSizes[i] : pagesPerProgram; for (int j = 0; j < x; j++) { tmp = i * pagesPerProgram + j; mainPageTable[tmp] = new Page(i, j, timestamp); pagesInMainMemory++; pageTables[i][j] = mainPageTable[tmp]; timestamp++; } } //Start reading in the program trace while(!programTraceIn.eof()) { programTraceIn >> requestingProgram; programTraceIn >> requestedPage; //Subtract 1 because the pages are 1-indexed for whatever reason requestedPage--; //Purposeful integer division, get floor of page requestedPage /= pageSize; //Page isn't resident if(pageTables[requestingProgram][requestedPage] == NULL) { pageFaults++; //There's space in main memory if(pagesInMainMemory != numFrames) { //Simply put the page at the end of the main table mainPageTable[pagesInMainMemory] = new Page(requestingProgram, requestedPage, timestamp); //Set the pointer pageTables[requestingProgram][requestedPage] = mainPageTable[pagesInMainMemory-1]; timestamp++; pagesInMainMemory++; } else { //Run a replacement algorithm replacePage(requestingProgram, requestedPage); //If we're using prepaging and requestedPage isn't the last logical page if(pagingMethod == "p" && requestedPage+1 < programSizes[requestingProgram]) { //If next page isn't resident if(pageTables[requestingProgram][requestedPage+1] == NULL) { replacePage(requestingProgram, requestedPage + 1); } else { //If using lru, update timestamp if(replacementAlgorithm == "lru") { pageTables[requestingProgram][requestedPage+1]->setTimestamp(timestamp); timestamp++; } else if(replacementAlgorithm == "clock") { pageTables[requestingProgram][requestedPage+1]->setUseBit(true); } } } } } else { //Page is resident //If using lru, update timestamp if(replacementAlgorithm == "lru") { pageTables[requestingProgram][requestedPage]->setTimestamp(timestamp); timestamp++; } else if(replacementAlgorithm == "clock") { pageTables[requestingProgram][requestedPage]->setUseBit(true); } } } //Close filestreams and delete data programListIn.close(); programTraceIn.close(); for(int i = 0; i < NUM_PROGRAMS; i++) { delete[] pageTables[i]; } for(int i = 0; i < numFrames; i++) { delete mainPageTable[i]; } delete[] mainPageTable; cout << "There were " << pageFaults << " page faults" << endl; return 0; } bool checkParameters(int argc, char* argv[], ifstream& programListIn, ifstream& programTraceIn, int& pageSize, string& replacementAlgorithm, string& pagingMethod) { bool pageSizeGood = false, replacementAlgorithmGood = false, pagingMethodGood = false; //Valid number of arguments, but some may not make sense if(argc == 6) { //Check to see if programList exists string filename = argv[1]; programListIn.open(filename + ".txt"); if(programListIn) { //File1 exists //Check to see if file2 exists filename = argv[2]; programTraceIn.open(filename + ".txt"); if(programTraceIn) { //File2 exists try { pageSize = std::stoi(argv[3]); //Page Size is numeric, but is it 1,2,4,8,16? for(int i = 0; i < 5; i++) { if(pageSize == std::pow(2, i)) { //It is pageSizeGood = true; break; } } if(pageSizeGood) { //Page size is good //Check replacement algorithm replacementAlgorithm = argv[4]; for(int i = 0; i < NUM_REPLACEMENT_ALGORITHMS; i++) { if(replacementAlgorithm == REPLACEMENT_ALGORITHMS[i]) { //Replacement algorithm is valid replacementAlgorithmGood = true; break; } } if(replacementAlgorithmGood) { //Replacement algorithm is valid //Check paging method pagingMethod = argv[5]; for(int i = 0; i < NUM_PAGING_METHODS; i++) { if(pagingMethod == PAGING_METHODS[i]) { pagingMethodGood = true; break; } } if(pagingMethodGood) { //Paging Method is valid //All Options are valid return true; } else { //Paging Method is invalid cerr << "Error: Paging Method " << pagingMethod << " is invalid." << endl; } } else { //It's not cerr << "Error: Page Replacement Algorithm " << replacementAlgorithm << " is invalid." << endl; } } else { //Page size isn't good cerr << "Error: " << pageSize << " is not a power of two." << endl; } } catch(std::invalid_argument e) { //Third argument is not an integer cerr << "Error: " << pageSize << " is not a numeric type." << endl; } } else { //It doesn't cerr << "Error: File " << argv[2] << ".txt does not exist. Please provide a valid filename" << endl; } } else { //It doesn't cerr << "Error: File " << argv[1] << ".txt does not exist. Please provide a valid filename" << endl; } } else { //Invalid number of parameters cerr << "Error: Invalid number of parameters provided. Please provide exactly 5 arguments." << endl; } cerr << endl; cerr << "Usage " << argv[0] << " programListFile programTraceFile numPages replacementAlgorithm pagingMethod" << endl; cerr << endl; cerr << "programListFile: The file containing the program list" << endl; cerr << "programTraceFile: The file containing the program trace" << endl; cerr << "numPages: The number of pages. Must be in the set {1,2,4,8,16}" << endl; cerr << "replacementAlgorithm: The replacement algorithm to use. Must be in the set {lru, fifo, clock}" << endl; cerr << "pagingMethod: The paging method to use. Must be in the set {p(Prepaging), d(Demand Paging)}" << endl; return false; } void replacePage(int requestingProgram, int requestedPage) { int indexOfPageToBeReplaced = 0; //LRU and FIFO replace pages the same way. The only difference is in how they update timestamps if(replacementAlgorithm == "lru" || replacementAlgorithm == "fifo") { indexOfPageToBeReplaced = getIndexOfOldestPage(); } else if(replacementAlgorithm == "clock") { //clockIndex = getIndexOfOldestPage(); while(mainPageTable[clockIndex]->getUseBit()) { //Clear the bit mainPageTable[clockIndex]->setUseBit(false); clockIndex++; clockIndex %= numFrames; } indexOfPageToBeReplaced = clockIndex; } //Replace page at index lruIndex Page p = *mainPageTable[indexOfPageToBeReplaced]; //Page p is no longer resident pageTables[p.getOwnerProgram()][p.getLogicalPageNum()] = NULL; delete mainPageTable[indexOfPageToBeReplaced]; mainPageTable[indexOfPageToBeReplaced] = new Page(requestingProgram, requestedPage, timestamp); pageTables[requestingProgram][requestedPage] = mainPageTable[indexOfPageToBeReplaced]; timestamp++; } int getIndexOfOldestPage() { int index = 0; //Find index of page with oldest timestamp for(int i = 0; i < numFrames; i++) { if(mainPageTable[i]->getTimestamp() < mainPageTable[index]->getTimestamp()) { index = i; } } return index; }<|endoftext|>
<commit_before>#include <iostream> #include <signal.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <strings.h> #include <pthread.h> #include <unistd.h> #include <string.h> using std::cout; using std::cin; using std::endl; using std::string; const int PORT_NUMBER = 9993; void controlCSignalHandler(int signal); void* readFromServer(void* argument); void* writeToServer(void* argument); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; const int BUFFER_SIZE = 512; int socketNum = -1; char buffer[BUFFER_SIZE]; const string QUIT_COMMAND = "/quit"; string username = ""; int main(int argc, char* argv[]) { struct sockaddr_in host = {AF_INET, htons(PORT_NUMBER)}; struct hostent *hostPointer; pthread_t readThread, writeThread; //A single CLI argument. Hopefully it's the hostname if(argc == 2) { //Tell the OS to run function 'controlCSignalHandler' when a SIGINT(ctl-c) signal is raised //Cool use of function pointers signal(SIGINT, controlCSignalHandler); //Get a pointer to a host hostPointer = gethostbyname(argv[1]); if(hostPointer != NULL) { //Copy our hostPointer address to our sockaddr_in struct bcopy( hostPointer->h_addr_list[0], (char*)&host.sin_addr, hostPointer->h_length ); //Reserve the socket socketNum = socket(AF_INET, SOCK_STREAM, 0); if(socketNum != -1) { if(connect(socketNum, (struct sockaddr*)&host, sizeof(host) ) != -1) { cout << "Connection successful!\nPlease enter a username: "; cin >> username; string str = username + " has joined the chat\n"; write(socketNum, str.c_str(), BUFFER_SIZE); //Try to create the reading thread if(pthread_create(&readThread, NULL, readFromServer, NULL) == 0) { if(pthread_create(&writeThread, NULL, writeToServer, NULL) == 0) { pthread_join(readThread, NULL); pthread_join(writeThread, NULL); pthread_exit(&writeThread); pthread_exit(&readThread); } else { cout << "Error: Could not create write thread" << endl; exit(1); } } else { cout << "Error: Could not create read thread" << endl; exit(1); } } else { cout << "Error: Socket connection failed. Please try again" << endl; exit(1); } } else { cout << "Error: Failed to bind to socket. Please try again"; exit(1); } } else { cout << "Error: Hostname \"" << argv[1] << "\" is not valid. Please try again" << endl; exit(1); } } else { std::cout << "Error: No hostname provided. Usage: " << argv[0] << " hostname" << endl; exit(1); } return 0; } void controlCSignalHandler(int signal) { cout << "Please don't exit the client with ctl-c. Only use /exit, /part, or /quit"; } void* readFromServer(void* argument) { cout << "Read from" << endl; string str; while(true) { pthread_mutex_lock(&mutex); read(socketNum, buffer, BUFFER_SIZE); str = buffer; pthread_mutex_unlock(&mutex); //Server told client to quit if(str == QUIT_COMMAND) { return NULL; } cout << str << endl; pthread_yield(); } } void* writeToServer(void* argument) { char* x; string sx = username + ": "; char* s = new char[BUFFER_SIZE]; strcpy(s, sx.c_str()); while(true) { strcpy(s, sx.c_str()); cout << sx; pthread_mutex_lock(&mutex); x = gets(buffer); if(x == NULL) { return NULL; } write(socketNum, strcat(s, buffer), BUFFER_SIZE); pthread_mutex_unlock(&mutex); pthread_yield(); } }<commit_msg>Got almost everything working. Just need to fix SIGINT handler<commit_after>#include <iostream> #include <signal.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <strings.h> #include <pthread.h> #include <unistd.h> #include <string.h> using std::cout; using std::cin; using std::endl; using std::string; const int PORT_NUMBER = 9993; void controlCSignalHandler(int signal); void* readFromServer(void* argument); void* writeToServer(void* argument); bool isQuitCommand(char* x); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; const int BUFFER_SIZE = 512; int socketNum = -1; const string QUIT_COMMAND = "/quit"; string username = ""; bool quitting = false; int main(int argc, char* argv[]) { struct sockaddr_in host = {AF_INET, htons(PORT_NUMBER)}; struct hostent *hostPointer; pthread_t readThread, writeThread; //A single CLI argument. Hopefully it's the hostname if(argc == 2) { //Tell the OS to run function 'controlCSignalHandler' when a SIGINT(ctl-c) signal is raised //Cool use of function pointers signal(SIGINT, controlCSignalHandler); //Get a pointer to a host hostPointer = gethostbyname(argv[1]); if(hostPointer != NULL) { //Copy our hostPointer address to our sockaddr_in struct bcopy( hostPointer->h_addr_list[0], (char*)&host.sin_addr, hostPointer->h_length ); //Reserve the socket socketNum = socket(AF_INET, SOCK_STREAM, 0); if(socketNum != -1) { if(connect(socketNum, (struct sockaddr*)&host, sizeof(host) ) != -1) { cout << "Connection successful!\nPlease enter a username: "; cin >> username; string str = username + " has joined the chat\n"; write(socketNum, str.c_str(), BUFFER_SIZE); //Try to create the reading thread if(pthread_create(&readThread, NULL, readFromServer, NULL) == 0) { if(pthread_create(&writeThread, NULL, writeToServer, NULL) == 0) { pthread_join(readThread, NULL); pthread_join(writeThread, NULL); pthread_exit(&writeThread); pthread_exit(&readThread); } else { cout << "Error: Could not create write thread" << endl; exit(1); } } else { cout << "Error: Could not create read thread" << endl; exit(1); } } else { cout << "Error: Socket connection failed. Please try again" << endl; exit(1); } } else { cout << "Error: Failed to bind to socket. Please try again"; exit(1); } } else { cout << "Error: Hostname \"" << argv[1] << "\" is not valid. Please try again" << endl; exit(1); } } else { cout << "Error: No hostname provided. Usage: " << argv[0] << " hostname" << endl; exit(1); } return 0; } void controlCSignalHandler(int signal) { cout << "Please don't exit the client with ctl-c. Only use /exit, /part, or /quit" << endl; } void* readFromServer(void* argument) { string str; char buffer[BUFFER_SIZE]; while(!quitting) { //pthread_mutex_lock(&mutex); read(socketNum, buffer, BUFFER_SIZE); str = buffer; //pthread_mutex_unlock(&mutex); //Server told client to quit if(str == QUIT_COMMAND) { quitting = true; } cout << str << endl; pthread_yield(); } } void* writeToServer(void* argument) { string message; char buffer[BUFFER_SIZE]; char* x; string sx = username + ": "; char* s = new char[BUFFER_SIZE]; strcpy(s, sx.c_str()); while(!quitting) { strcpy(s, sx.c_str()); //pthread_mutex_lock(&mutex); /*x = gets(buffer); if(x == NULL) { return NULL; }*/ cin >> message; strcpy(buffer, message.c_str()); if(isQuitCommand(buffer)) { cout << "Quitting..." << endl; quitting = true; } //Don't send blank lines if(strcmp(buffer, "") != 0) { write(socketNum, strcat(s, buffer), BUFFER_SIZE); } //pthread_mutex_unlock(&mutex); pthread_yield(); } } bool isQuitCommand(char* x) { return strcmp(x, "/quit") == 0 || strcmp(x, "/part") == 0 || strcmp(x, "/exit") == 0; }<|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "registration.h" #include <vistk/pipeline/process_registry.h> #include <vistk/pipeline/schedule_registry.h> #include <vistk/pipeline/utils.h> #include <boost/algorithm/string/split.hpp> #include <boost/foreach.hpp> #include <sstream> #include <Python.h> using namespace vistk; static envvar_name_t const python_suppress_envvar = envvar_name_t("VISTK_NO_PYTHON_MODULES"); static envvar_name_t const python_process_modules_envvar = envvar_name_t("VISTK_PYTHON_SCHEDULE_MODULES"); static envvar_name_t const python_schedule_modules_envvar = envvar_name_t("VISTK_PYTHON_PROCESS_MODULES"); static std::string const standard_python_process_module = "vistk.processes"; static std::string const standard_python_schedule_module = "vistk.schedules"; static bool is_suppressed(); static void load_from_module(std::string const& module, std::string const& function); static bool is_separator(char ch); void register_processes() { if (is_suppressed()) { return; } std::vector<std::string> modules; modules.push_back(standard_python_process_module); // Load extra modules given via the environment. { envvar_value_t const python_modules = get_envvar(python_process_modules_envvar); if (python_modules) { boost::split(modules, python_modules, is_separator, boost::token_compress_on); } free_envvar(python_modules); } Py_Initialize(); static process_registry::module_t const base_module_name = process_registry::module_t("python_process_module:"); process_registry_t const registry = process_registry::self(); BOOST_FOREACH (std::string const& module, modules) { process_registry::module_t const module_name = base_module_name + process_registry::module_t(module); if (registry->is_module_loaded(module_name)) { continue; } std::string const function = "register_processes"; load_from_module(module, function); registry->mark_module_as_loaded(module_name); } } void register_schedules() { if (is_suppressed()) { return; } std::vector<std::string> modules; modules.push_back(standard_python_schedule_module); // Load extra modules given via the environment. { envvar_value_t const python_modules = get_envvar(python_schedule_modules_envvar); if (python_modules) { boost::split(modules, python_modules, is_separator, boost::token_compress_on); } free_envvar(python_modules); } Py_Initialize(); static schedule_registry::module_t const base_module_name = schedule_registry::module_t("python_schedule_module:"); schedule_registry_t const registry = schedule_registry::self(); BOOST_FOREACH (std::string const& module, modules) { schedule_registry::module_t const module_name = base_module_name + schedule_registry::module_t(module); if (registry->is_module_loaded(module_name)) { continue; } std::string const function = "register_schedule"; load_from_module(module, function); registry->mark_module_as_loaded(module_name); } } bool is_suppressed() { envvar_value_t const python_suppress = get_envvar(python_suppress_envvar); bool suppress_python_modules = false; if (python_suppress) { suppress_python_modules = true; } free_envvar(python_suppress); if (suppress_python_modules) { return true; } return false; } void load_from_module(std::string const& module, std::string const& function) { std::stringstream sstr; sstr << "import " << module << std::endl; sstr << "if hasattr(" << module << ", \'" << function << "\'):" << std::endl; sstr << " if callable(" << module << "." << function << "):" << std::endl; sstr << " " << module << "." << function << "()" << std::endl; PyRun_SimpleString(sstr.str().c_str()); } bool is_separator(char ch) { char const separator = #if defined(_WIN32) || defined(_WIN64) ';'; #else ':'; #endif return (ch == separator); } <commit_msg>Fix up useage of boost::split<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "registration.h" #include <vistk/pipeline/process_registry.h> #include <vistk/pipeline/schedule_registry.h> #include <vistk/pipeline/utils.h> #include <boost/algorithm/string/split.hpp> #include <boost/foreach.hpp> #include <sstream> #include <Python.h> using namespace vistk; static envvar_name_t const python_suppress_envvar = envvar_name_t("VISTK_NO_PYTHON_MODULES"); static envvar_name_t const python_process_modules_envvar = envvar_name_t("VISTK_PYTHON_SCHEDULE_MODULES"); static envvar_name_t const python_schedule_modules_envvar = envvar_name_t("VISTK_PYTHON_PROCESS_MODULES"); static std::string const standard_python_process_module = "vistk.processes"; static std::string const standard_python_schedule_module = "vistk.schedules"; static bool is_suppressed(); static void load_from_module(std::string const& module, std::string const& function); static bool is_separator(char ch); void register_processes() { if (is_suppressed()) { return; } std::vector<std::string> modules; modules.push_back(standard_python_process_module); // Load extra modules given via the environment. { envvar_value_t const python_modules = get_envvar(python_process_modules_envvar); if (python_modules) { /// \bug Boost <= 1.47 boost::split *overwrites* destination. std::vector<std::string> modules_tmp; boost::split(modules_tmp, python_modules, is_separator, boost::token_compress_on); modules.insert(modules.end(), modules.begin(), modules_tmp.end()); } free_envvar(python_modules); } Py_Initialize(); static process_registry::module_t const base_module_name = process_registry::module_t("python_process_module:"); process_registry_t const registry = process_registry::self(); BOOST_FOREACH (std::string const& module, modules) { process_registry::module_t const module_name = base_module_name + process_registry::module_t(module); if (registry->is_module_loaded(module_name)) { continue; } std::string const function = "register_processes"; load_from_module(module, function); registry->mark_module_as_loaded(module_name); } } void register_schedules() { if (is_suppressed()) { return; } std::vector<std::string> modules; modules.push_back(standard_python_schedule_module); // Load extra modules given via the environment. { envvar_value_t const python_modules = get_envvar(python_schedule_modules_envvar); if (python_modules) { /// \bug Boost <= 1.47 boost::split *overwrites* destination. std::vector<std::string> modules_tmp; boost::split(modules_tmp, python_modules, is_separator, boost::token_compress_on); modules.insert(modules.end(), modules.begin(), modules_tmp.end()); } free_envvar(python_modules); } Py_Initialize(); static schedule_registry::module_t const base_module_name = schedule_registry::module_t("python_schedule_module:"); schedule_registry_t const registry = schedule_registry::self(); BOOST_FOREACH (std::string const& module, modules) { schedule_registry::module_t const module_name = base_module_name + schedule_registry::module_t(module); if (registry->is_module_loaded(module_name)) { continue; } std::string const function = "register_schedule"; load_from_module(module, function); registry->mark_module_as_loaded(module_name); } } bool is_suppressed() { envvar_value_t const python_suppress = get_envvar(python_suppress_envvar); bool suppress_python_modules = false; if (python_suppress) { suppress_python_modules = true; } free_envvar(python_suppress); if (suppress_python_modules) { return true; } return false; } void load_from_module(std::string const& module, std::string const& function) { std::stringstream sstr; sstr << "import " << module << std::endl; sstr << "if hasattr(" << module << ", \'" << function << "\'):" << std::endl; sstr << " if callable(" << module << "." << function << "):" << std::endl; sstr << " " << module << "." << function << "()" << std::endl; PyRun_SimpleString(sstr.str().c_str()); } bool is_separator(char ch) { char const separator = #if defined(_WIN32) || defined(_WIN64) ';'; #else ':'; #endif return (ch == separator); } <|endoftext|>
<commit_before>#include <boost/python.hpp> #include <Magick++/Drawable.h> #include <Magick++.h> using namespace boost; using namespace boost::python; void __Drawable() { implicitly_convertible< Magick::DrawableBase, Magick::Drawable >(); class_< Magick::DrawableBase, noncopyable >("DrawableBase", no_init) ; class_< Magick::Drawable >("Drawable", init< >()) .def(init< const Magick::DrawableBase& >()) .def(init< const Magick::Drawable& >()) .def( self != self ) .def( self == self ) .def( self < self ) .def( self > self ) .def( self <= self ) .def( self >= self ) ; class_< Magick::DrawableList >("DrawableList", init< >()) .def(init< const Magick::DrawableList& >()) .def("push_back", &std::list<Magick::Drawable>::push_back) .def("append", &std::list<Magick::Drawable>::push_back) .def("pop_back", &std::list<Magick::Drawable>::pop_back) .def("pop", &std::list<Magick::Drawable>::pop_back) .def("remove", &std::list<Magick::Drawable>::remove) .def("reverse", &std::list<Magick::Drawable>::reverse) .def("count", &std::list<Magick::Drawable>::size) .def("__len__", &std::list<Magick::Drawable>::size) ; } <commit_msg>implement CoordinateList<commit_after>#include <boost/python.hpp> #include <Magick++/Drawable.h> #include <Magick++.h> using namespace boost; using namespace boost::python; void __Drawable() { implicitly_convertible< Magick::DrawableBase, Magick::Drawable >(); class_< Magick::DrawableBase, noncopyable >("DrawableBase", no_init) ; class_< Magick::Drawable >("Drawable", init< >()) .def(init< const Magick::DrawableBase& >()) .def(init< const Magick::Drawable& >()) .def( self != self ) .def( self == self ) .def( self < self ) .def( self > self ) .def( self <= self ) .def( self >= self ) ; class_< Magick::DrawableList >("DrawableList", init< >()) .def(init< const Magick::DrawableList& >()) .def("push_back", &std::list<Magick::Drawable>::push_back) .def("append", &std::list<Magick::Drawable>::push_back) .def("pop_back", &std::list<Magick::Drawable>::pop_back) .def("pop", &std::list<Magick::Drawable>::pop_back) .def("remove", &std::list<Magick::Drawable>::remove) .def("reverse", &std::list<Magick::Drawable>::reverse) .def("count", &std::list<Magick::Drawable>::size) .def("__len__", &std::list<Magick::Drawable>::size) ; class_< Magick::CoordinateList >("CoordinateList", init< >()) .def(init< const Magick::CoordinateList& >()) .def("push_back", &std::list<Magick::Coordinate>::push_back) .def("append", &std::list<Magick::Coordinate>::push_back) .def("pop_back", &std::list<Magick::Coordinate>::pop_back) .def("pop", &std::list<Magick::Coordinate>::pop_back) .def("remove", &std::list<Magick::Coordinate>::remove) .def("reverse", &std::list<Magick::Coordinate>::reverse) .def("count", &std::list<Magick::Coordinate>::size) .def("__len__", &std::list<Magick::Coordinate>::size) ; } <|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> #include <abaclade/perf/stopwatch.hxx> #if ABC_HOST_API_POSIX #include <time.h> #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::perf::stopwatch namespace abc { namespace perf { namespace { #if ABC_HOST_API_POSIX std::pair<bool, ::clockid_t> get_timer_clock() { ::clockid_t clkid; // Try and get a timer specific to this process. if (::clock_getcpuclockid(0, &clkid) == 0) { return std::make_pair(true, std::move(clkid)); } #if defined(CLOCK_PROCESS_CPUTIME_ID) return std::make_pair(true, CLOCK_PROCESS_CPUTIME_ID); #endif //if defined(CLOCK_PROCESS_CPUTIME_ID) // No suitable timer to use. return std::make_pair(false, ::clockid_t()); } ::timespec get_time_point() { auto clkidTimer = get_timer_clock(); if (!clkidTimer.first) { // No suitable timer to use. // TODO: do something other than throw. throw 0; } ::timespec tsRet; ::clock_gettime(clkidTimer.second, &tsRet); return std::move(tsRet); } std::uint64_t get_duration_ns(::timespec const & tsBegin, ::timespec const & tsEnd) { ABC_TRACE_FUNC(); std::int64_t iInterval = (tsEnd.tv_sec - tsBegin.tv_sec) * 1000000; iInterval = iInterval + tsEnd.tv_nsec - tsBegin.tv_nsec; return static_cast<std::uint64_t>(iInterval); } #elif ABC_HOST_API_WIN32 //if ABC_HOST_API_POSIX ::FILETIME get_time_point() { ::FILETIME ftRet, ftUnused; ::GetProcessTimes(::GetCurrentProcess(), &ftUnused, &ftUnused, &ftUnused, &ftRet); return std::move(ftRet); } std::uint64_t get_duration_ns(::FILETIME const & ftBegin, ::FILETIME const & ftEnd) { ABC_TRACE_FUNC(); // Compose the FILETIME arguments into 64-bit integers. ULARGE_INTEGER iBegin, iEnd; iBegin.LowPart = ftBegin.dwLowDateTime; iBegin.HighPart = ftBegin.dwHighDateTime; iEnd.LowPart = ftEnd.dwLowDateTime; iEnd.HighPart = ftEnd.dwHighDateTime; // FILETIME is in units of 100 ns, so scale it to 1 ns. return (iEnd.QuadPart - iBegin.QuadPart) * 100; } #else //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 // We could probably just use std::chrono here. #error "TODO: HOST_API" #endif //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else } //namespace stopwatch::stopwatch() : m_iTotalDuration(0) { } stopwatch::~stopwatch() { } void stopwatch::start() { ABC_TRACE_FUNC(this); *reinterpret_cast<decltype(get_time_point()) *>(&m_abStartTime) = get_time_point(); } std::uint64_t stopwatch::stop() { auto timepoint(get_time_point()); // We do this here to avoid adding ABC_TRACE_FUNC() to the timed execution. ABC_TRACE_FUNC(this); std::uint64_t iPartialDuration = get_duration_ns( *reinterpret_cast<decltype(timepoint) *>(&m_abStartTime), timepoint ); m_iTotalDuration += iPartialDuration; return iPartialDuration; } } //namespace perf } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <commit_msg>Fix abc::perf::stopwatch::get_duration_ns() time unit conversion<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> #include <abaclade/perf/stopwatch.hxx> #if ABC_HOST_API_POSIX #include <time.h> #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::perf::stopwatch namespace abc { namespace perf { namespace { #if ABC_HOST_API_POSIX std::pair<bool, ::clockid_t> get_timer_clock() { ::clockid_t clkid; // Try and get a timer specific to this process. if (::clock_getcpuclockid(0, &clkid) == 0) { return std::make_pair(true, std::move(clkid)); } #if defined(CLOCK_PROCESS_CPUTIME_ID) return std::make_pair(true, CLOCK_PROCESS_CPUTIME_ID); #endif //if defined(CLOCK_PROCESS_CPUTIME_ID) // No suitable timer to use. return std::make_pair(false, ::clockid_t()); } ::timespec get_time_point() { auto clkidTimer = get_timer_clock(); if (!clkidTimer.first) { // No suitable timer to use. // TODO: do something other than throw. throw 0; } ::timespec tsRet; ::clock_gettime(clkidTimer.second, &tsRet); return std::move(tsRet); } std::uint64_t get_duration_ns(::timespec const & tsBegin, ::timespec const & tsEnd) { ABC_TRACE_FUNC(); std::uint64_t iInterval = static_cast<std::uint64_t>(tsEnd.tv_sec - tsBegin.tv_sec) * 1000000000; iInterval += static_cast<std::uint64_t>(tsEnd.tv_nsec); iInterval -= static_cast<std::uint64_t>(tsBegin.tv_nsec); return static_cast<std::uint64_t>(iInterval); } #elif ABC_HOST_API_WIN32 //if ABC_HOST_API_POSIX ::FILETIME get_time_point() { ::FILETIME ftRet, ftUnused; ::GetProcessTimes(::GetCurrentProcess(), &ftUnused, &ftUnused, &ftUnused, &ftRet); return std::move(ftRet); } std::uint64_t get_duration_ns(::FILETIME const & ftBegin, ::FILETIME const & ftEnd) { ABC_TRACE_FUNC(); // Compose the FILETIME arguments into 64-bit integers. ULARGE_INTEGER iBegin, iEnd; iBegin.LowPart = ftBegin.dwLowDateTime; iBegin.HighPart = ftBegin.dwHighDateTime; iEnd.LowPart = ftEnd.dwLowDateTime; iEnd.HighPart = ftEnd.dwHighDateTime; // FILETIME is in units of 100 ns, so scale it to 1 ns. return (iEnd.QuadPart - iBegin.QuadPart) * 100; } #else //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 // We could probably just use std::chrono here. #error "TODO: HOST_API" #endif //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else } //namespace stopwatch::stopwatch() : m_iTotalDuration(0) { } stopwatch::~stopwatch() { } void stopwatch::start() { ABC_TRACE_FUNC(this); *reinterpret_cast<decltype(get_time_point()) *>(&m_abStartTime) = get_time_point(); } std::uint64_t stopwatch::stop() { auto timepoint(get_time_point()); // We do this here to avoid adding ABC_TRACE_FUNC() to the timed execution. ABC_TRACE_FUNC(this); std::uint64_t iPartialDuration = get_duration_ns( *reinterpret_cast<decltype(timepoint) *>(&m_abStartTime), timepoint ); m_iTotalDuration += iPartialDuration; return iPartialDuration; } } //namespace perf } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson * * Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * For comments regarding functions please see the header file. */ #include "guichan/allegro/allegrographics.hpp" #include "guichan/allegro/allegroimage.hpp" #include "guichan/rectangle.hpp" #include "guichan/exception.hpp" #include "guichan/cliprectangle.hpp" #include "guichan/color.hpp" namespace gcn { AllegroGraphics::AllegroGraphics() { mTarget = NULL; mClipNull = false; } AllegroGraphics::AllegroGraphics(BITMAP *target) { mTarget = target; } AllegroGraphics::~AllegroGraphics() { } void AllegroGraphics::setTarget(BITMAP *target) { mTarget = target; } BITMAP *AllegroGraphics::getTarget() { return mTarget; } void AllegroGraphics::_beginDraw() { if (mTarget == NULL) { throw GCN_EXCEPTION("Target BITMAP is null, set it with setTarget first."); } // push a clip area the size of the target bitmap pushClipArea(Rectangle(0, 0, mTarget->w, mTarget->h)); } void AllegroGraphics::_endDraw() { // pop the clip area pushed in _beginDraw popClipArea(); } bool AllegroGraphics::pushClipArea(Rectangle area) { bool result = Graphics::pushClipArea(area); const ClipRectangle& cr = mClipStack.top(); // Allegro won't let you set clip areas // that have zero width or height // so we have to check for that. if (cr.width == 0 || cr.height == 0) { mClipNull = true; } else { mClipNull = false; #if ALLEGRO_VERSION == 4 && ALLEGRO_SUB_VERSION == 0 set_clip(mTarget, cr.x, cr.y, cr.x + cr.width - 1, cr.y + cr.height - 1); #else set_clip_rect(mTarget, cr.x, cr.y, cr.x + cr.width - 1, cr.y + cr.height - 1); #endif } return result; } void AllegroGraphics::popClipArea() { Graphics::popClipArea(); if (mClipStack.empty()) { return; } const ClipRectangle& cr = mClipStack.top(); // Allegro won't let you set clip areas //that have zero width or height // so we have to check for that. if (cr.width == 0 || cr.height == 0) { mClipNull = true; } else { mClipNull = false; #if ALLEGRO_VERSION == 4 && ALLEGRO_SUB_VERSION == 0 set_clip(mTarget, cr.x, cr.y, cr.x + cr.width - 1, cr.y + cr.height - 1); #else set_clip_rect(mTarget, cr.x, cr.y, cr.x + cr.width - 1, cr.y + cr.height - 1); #endif } } void AllegroGraphics::drawImage(const Image* image, int srcX, int srcY, int dstX, int dstY, int width, int height) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; const AllegroImage* srcImage = dynamic_cast<const AllegroImage*>(image); if (srcImage == NULL) { throw GCN_EXCEPTION("Trying to draw an image of unknown format, must be an AllegroImage."); } masked_blit(srcImage->getBitmap(), mTarget, srcX, srcY, dstX + xOffset, dstY + yOffset, width, height); } void AllegroGraphics::drawPoint(int x, int y) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; putpixel(mTarget, x + xOffset, y + yOffset, mAlColor); } void AllegroGraphics::drawLine(int x1, int y1, int x2, int y2) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; line(mTarget, x1 + xOffset, y1 + yOffset, x2 + xOffset, y2 + yOffset, mAlColor); } void AllegroGraphics::drawRectangle(const Rectangle& rectangle) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; rect(mTarget, rectangle.x + xOffset, rectangle.y + yOffset, rectangle.x + rectangle.width - 1 + xOffset, rectangle.y + rectangle.height - 1 + yOffset, mAlColor); } void AllegroGraphics::fillRectangle(const Rectangle& rectangle) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; rectfill(mTarget, rectangle.x + xOffset, rectangle.y + yOffset, rectangle.x + rectangle.width - 1 + xOffset, rectangle.y + rectangle.height - 1 + yOffset, mAlColor); } void AllegroGraphics::setColor(const Color& color) { mColor = color; mAlColor = makecol(color.r, color.g, color.b); if (color.a != 255) { set_trans_blender(255, 255, 255, color.a); drawing_mode(DRAW_MODE_TRANS, NULL, 0, 0); } else { solid_mode(); } } const Color& AllegroGraphics::getColor() { return mColor; } } <commit_msg>getAllegroColor has been added. mAlColor has been renamed to mAllegroColor.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson * * Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * For comments regarding functions please see the header file. */ #include "guichan/allegro/allegrographics.hpp" #include "guichan/allegro/allegroimage.hpp" #include "guichan/rectangle.hpp" #include "guichan/exception.hpp" #include "guichan/cliprectangle.hpp" #include "guichan/color.hpp" namespace gcn { AllegroGraphics::AllegroGraphics() { mTarget = NULL; mClipNull = false; } AllegroGraphics::AllegroGraphics(BITMAP *target) { mTarget = target; } AllegroGraphics::~AllegroGraphics() { } void AllegroGraphics::setTarget(BITMAP *target) { mTarget = target; } BITMAP *AllegroGraphics::getTarget() { return mTarget; } void AllegroGraphics::_beginDraw() { if (mTarget == NULL) { throw GCN_EXCEPTION("Target BITMAP is null, set it with setTarget first."); } // push a clip area the size of the target bitmap pushClipArea(Rectangle(0, 0, mTarget->w, mTarget->h)); } void AllegroGraphics::_endDraw() { // pop the clip area pushed in _beginDraw popClipArea(); } bool AllegroGraphics::pushClipArea(Rectangle area) { bool result = Graphics::pushClipArea(area); const ClipRectangle& cr = mClipStack.top(); // Allegro won't let you set clip areas // that have zero width or height // so we have to check for that. if (cr.width == 0 || cr.height == 0) { mClipNull = true; } else { mClipNull = false; #if ALLEGRO_VERSION == 4 && ALLEGRO_SUB_VERSION == 0 set_clip(mTarget, cr.x, cr.y, cr.x + cr.width - 1, cr.y + cr.height - 1); #else set_clip_rect(mTarget, cr.x, cr.y, cr.x + cr.width - 1, cr.y + cr.height - 1); #endif } return result; } void AllegroGraphics::popClipArea() { Graphics::popClipArea(); if (mClipStack.empty()) { return; } const ClipRectangle& cr = mClipStack.top(); // Allegro won't let you set clip areas //that have zero width or height // so we have to check for that. if (cr.width == 0 || cr.height == 0) { mClipNull = true; } else { mClipNull = false; #if ALLEGRO_VERSION == 4 && ALLEGRO_SUB_VERSION == 0 set_clip(mTarget, cr.x, cr.y, cr.x + cr.width - 1, cr.y + cr.height - 1); #else set_clip_rect(mTarget, cr.x, cr.y, cr.x + cr.width - 1, cr.y + cr.height - 1); #endif } } void AllegroGraphics::drawImage(const Image* image, int srcX, int srcY, int dstX, int dstY, int width, int height) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion " "outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; const AllegroImage* srcImage = dynamic_cast<const AllegroImage*>(image); if (srcImage == NULL) { throw GCN_EXCEPTION("Trying to draw an image of unknown format, must be an AllegroImage."); } masked_blit(srcImage->getBitmap(), mTarget, srcX, srcY, dstX + xOffset, dstY + yOffset, width, height); } void AllegroGraphics::drawPoint(int x, int y) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion " "outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; putpixel(mTarget, x + xOffset, y + yOffset, mAllegroColor); } void AllegroGraphics::drawLine(int x1, int y1, int x2, int y2) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion " "outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; line(mTarget, x1 + xOffset, y1 + yOffset, x2 + xOffset, y2 + yOffset, mAllegroColor); } void AllegroGraphics::drawRectangle(const Rectangle& rectangle) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion " "outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; rect(mTarget, rectangle.x + xOffset, rectangle.y + yOffset, rectangle.x + rectangle.width - 1 + xOffset, rectangle.y + rectangle.height - 1 + yOffset, mAllegroColor); } void AllegroGraphics::fillRectangle(const Rectangle& rectangle) { if (mClipNull) { return; } if (mClipStack.empty()) { throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion " "outside of _beginDraw() and _endDraw()?"); } const int xOffset = mClipStack.top().xOffset; const int yOffset = mClipStack.top().yOffset; rectfill(mTarget, rectangle.x + xOffset, rectangle.y + yOffset, rectangle.x + rectangle.width - 1 + xOffset, rectangle.y + rectangle.height - 1 + yOffset, mAllegroColor); } void AllegroGraphics::setColor(const Color& color) { mColor = color; mAllegroColor = makecol(color.r, color.g, color.b); if (color.a != 255) { set_trans_blender(255, 255, 255, color.a); drawing_mode(DRAW_MODE_TRANS, NULL, 0, 0); } else { solid_mode(); } } const Color& AllegroGraphics::getColor() { return mColor; } int AllegroGraphics::getAllegroColor() const { return mAllegroColor; } } <|endoftext|>
<commit_before>/* * SpriteBatch.cpp * moFlo * * Created by Scott Downie on 06/10/2010. * Copyright 2010 Tag Games. All rights reserved. * */ #include <ChilliSource/Rendering/Sprite/DynamicSpriteBatcher.h> #include <ChilliSource/Rendering/Base/RenderSystem.h> #include <ChilliSource/Core/Math/MathUtils.h> #ifdef CS_ENABLE_DEBUGSTATS #include <ChilliSource/Debugging/Base/DebugStats.h> #endif namespace ChilliSource { namespace Rendering { const u32 kudwMaxSpritesInDynamicBatch = 2048; //------------------------------------------------------- /// Constructor /// /// Default //------------------------------------------------------- DynamicSpriteBatch::DynamicSpriteBatch(RenderSystem* inpRenderSystem) : mudwCurrentRenderSpriteBatch(0), mudwSpriteCommandCounter(0) { for(u32 i=0; i<kudwNumBuffers; ++i) { mpBatch[i] = new SpriteBatch(kudwMaxSpritesInDynamicBatch, inpRenderSystem, BufferUsage::k_dynamic); } maRenderCommands.reserve(50); } //------------------------------------------------------- /// Render /// /// Batch the sprite to be rendered later. Track the /// render commands so that the correct subset of the /// mesh buffer can be flushed and the correct material /// applied /// /// @param Render system /// @param Sprite data to batch //------------------------------------------------------- void DynamicSpriteBatch::Render(RenderSystem* inpRenderSystem, const SpriteComponent::SpriteData& inpSprite, const Core::Matrix4x4 * inpTransform) { //If we exceed the capacity of the buffer then we will be forced to flush it if(maSpriteCache.size() >= kudwMaxSpritesInDynamicBatch) { ForceRender(inpRenderSystem); } //As all the contents of the mesh buffer have the same vertex format we can push sprites into the buffer //regardless of the material. However we cannot render the buffer in a single draw call we must render //subsets of the buffer based on materials if(mpLastMaterial && mpLastMaterial != inpSprite.pMaterial) { ForceCommandChange(); } maSpriteCache.push_back(inpSprite); if(inpTransform) { for(u32 i = 0; i < kudwVertsPerSprite; i++) Core::Matrix4x4::Multiply(&inpSprite.sVerts[i].vPos, inpTransform, &maSpriteCache.back().sVerts[i].vPos); } mpLastMaterial = inpSprite.pMaterial; ++mudwSpriteCommandCounter; } //------------------------------------------------------- /// Force Command Change /// /// Force a render command change so that subsequent /// additons to the buffer will not be drawn in this call //------------------------------------------------------- void DynamicSpriteBatch::ForceCommandChange() { if(!maSpriteCache.empty()) { maRenderCommands.resize(maRenderCommands.size() + 1); RenderCommand &sLastCommand = maRenderCommands.back(); //Make a copy of the material that this batch will use sLastCommand.m_material = *(mpLastMaterial.get()); //The offset of the indices for this batch sLastCommand.m_offset = ((maSpriteCache.size() - mudwSpriteCommandCounter) * kudwIndicesPerSprite) * sizeof(s16); //The number of indices in this batch sLastCommand.m_stride = mudwSpriteCommandCounter * kudwIndicesPerSprite; mudwSpriteCommandCounter = 0; } } //------------------------------------------------------- /// Force Render /// /// Force the currently batched sprites to be rendered /// regardless of whether the batch is full /// /// @param Render system //------------------------------------------------------- void DynamicSpriteBatch::ForceRender(RenderSystem* inpRenderSystem) { if(!maSpriteCache.empty()) { #ifdef CS_ENABLE_DEBUGSTATS if(!maRenderCommands.empty()) { RenderCommand &sLastCommand = maRenderCommands.back(); if(sLastCommand.Material.IsTransparent()) { DebugStats::AddToEvent("Sprites_Trans", (u32)maSpriteCache.size()); } else { DebugStats::AddToEvent("Sprites", (u32)maSpriteCache.size()); } } #endif //Close off the batch ForceCommandChange(); //Copy geometry into the mesh buffer and render BuildAndFlushBatch(inpRenderSystem); } } //---------------------------------------------------------- /// Build and Flush Batch /// /// Map the batch into the mesh buffer and present the /// contents. This will then swap the active buffer /// so that it can be filled while the other one is /// rendering /// /// @param Render system //---------------------------------------------------------- void DynamicSpriteBatch::BuildAndFlushBatch(RenderSystem* inpRenderSystem) { if(!maSpriteCache.empty()) { //Build the next buffer mpBatch[mudwCurrentRenderSpriteBatch]->Build(&maSpriteCache); maSpriteCache.clear(); } //Loop round all the render commands and draw the sections of the buffer with the correct material for(std::vector<RenderCommand>::iterator it = maRenderCommands.begin(); it != maRenderCommands.end(); ++it) { //Render the last filled buffer mpBatch[mudwCurrentRenderSpriteBatch]->Render(inpRenderSystem, it->m_material, it->m_offset, it->m_stride); } maRenderCommands.clear(); mpLastMaterial.reset(); //Swap the buffers mudwCurrentRenderSpriteBatch = Core::MathUtils::Wrap(++mudwCurrentRenderSpriteBatch, 0u, kudwBufferArrayBounds); } //---------------------------------------------------------- /// Destructor //---------------------------------------------------------- DynamicSpriteBatch::~DynamicSpriteBatch() { for(u32 i=0; i<kudwNumBuffers; ++i) { delete mpBatch[i]; } } } } <commit_msg>reduced the size of the dynamic sprite batch buffer to 25% of it's previous size.<commit_after>/* * SpriteBatch.cpp * moFlo * * Created by Scott Downie on 06/10/2010. * Copyright 2010 Tag Games. All rights reserved. * */ #include <ChilliSource/Rendering/Sprite/DynamicSpriteBatcher.h> #include <ChilliSource/Rendering/Base/RenderSystem.h> #include <ChilliSource/Core/Math/MathUtils.h> #ifdef CS_ENABLE_DEBUGSTATS #include <ChilliSource/Debugging/Base/DebugStats.h> #endif namespace ChilliSource { namespace Rendering { const u32 kudwMaxSpritesInDynamicBatch = 512; //------------------------------------------------------- /// Constructor /// /// Default //------------------------------------------------------- DynamicSpriteBatch::DynamicSpriteBatch(RenderSystem* inpRenderSystem) : mudwCurrentRenderSpriteBatch(0), mudwSpriteCommandCounter(0) { for(u32 i=0; i<kudwNumBuffers; ++i) { mpBatch[i] = new SpriteBatch(kudwMaxSpritesInDynamicBatch, inpRenderSystem, BufferUsage::k_dynamic); } maRenderCommands.reserve(50); } //------------------------------------------------------- /// Render /// /// Batch the sprite to be rendered later. Track the /// render commands so that the correct subset of the /// mesh buffer can be flushed and the correct material /// applied /// /// @param Render system /// @param Sprite data to batch //------------------------------------------------------- void DynamicSpriteBatch::Render(RenderSystem* inpRenderSystem, const SpriteComponent::SpriteData& inpSprite, const Core::Matrix4x4 * inpTransform) { //If we exceed the capacity of the buffer then we will be forced to flush it if(maSpriteCache.size() >= kudwMaxSpritesInDynamicBatch) { ForceRender(inpRenderSystem); } //As all the contents of the mesh buffer have the same vertex format we can push sprites into the buffer //regardless of the material. However we cannot render the buffer in a single draw call we must render //subsets of the buffer based on materials if(mpLastMaterial && mpLastMaterial != inpSprite.pMaterial) { ForceCommandChange(); } maSpriteCache.push_back(inpSprite); if(inpTransform) { for(u32 i = 0; i < kudwVertsPerSprite; i++) Core::Matrix4x4::Multiply(&inpSprite.sVerts[i].vPos, inpTransform, &maSpriteCache.back().sVerts[i].vPos); } mpLastMaterial = inpSprite.pMaterial; ++mudwSpriteCommandCounter; } //------------------------------------------------------- /// Force Command Change /// /// Force a render command change so that subsequent /// additons to the buffer will not be drawn in this call //------------------------------------------------------- void DynamicSpriteBatch::ForceCommandChange() { if(!maSpriteCache.empty()) { maRenderCommands.resize(maRenderCommands.size() + 1); RenderCommand &sLastCommand = maRenderCommands.back(); //Make a copy of the material that this batch will use sLastCommand.m_material = *(mpLastMaterial.get()); //The offset of the indices for this batch sLastCommand.m_offset = ((maSpriteCache.size() - mudwSpriteCommandCounter) * kudwIndicesPerSprite) * sizeof(s16); //The number of indices in this batch sLastCommand.m_stride = mudwSpriteCommandCounter * kudwIndicesPerSprite; mudwSpriteCommandCounter = 0; } } //------------------------------------------------------- /// Force Render /// /// Force the currently batched sprites to be rendered /// regardless of whether the batch is full /// /// @param Render system //------------------------------------------------------- void DynamicSpriteBatch::ForceRender(RenderSystem* inpRenderSystem) { if(!maSpriteCache.empty()) { #ifdef CS_ENABLE_DEBUGSTATS if(!maRenderCommands.empty()) { RenderCommand &sLastCommand = maRenderCommands.back(); if(sLastCommand.Material.IsTransparent()) { DebugStats::AddToEvent("Sprites_Trans", (u32)maSpriteCache.size()); } else { DebugStats::AddToEvent("Sprites", (u32)maSpriteCache.size()); } } #endif //Close off the batch ForceCommandChange(); //Copy geometry into the mesh buffer and render BuildAndFlushBatch(inpRenderSystem); } } //---------------------------------------------------------- /// Build and Flush Batch /// /// Map the batch into the mesh buffer and present the /// contents. This will then swap the active buffer /// so that it can be filled while the other one is /// rendering /// /// @param Render system //---------------------------------------------------------- void DynamicSpriteBatch::BuildAndFlushBatch(RenderSystem* inpRenderSystem) { if(!maSpriteCache.empty()) { //Build the next buffer mpBatch[mudwCurrentRenderSpriteBatch]->Build(&maSpriteCache); maSpriteCache.clear(); } //Loop round all the render commands and draw the sections of the buffer with the correct material for(std::vector<RenderCommand>::iterator it = maRenderCommands.begin(); it != maRenderCommands.end(); ++it) { //Render the last filled buffer mpBatch[mudwCurrentRenderSpriteBatch]->Render(inpRenderSystem, it->m_material, it->m_offset, it->m_stride); } maRenderCommands.clear(); mpLastMaterial.reset(); //Swap the buffers mudwCurrentRenderSpriteBatch = Core::MathUtils::Wrap(++mudwCurrentRenderSpriteBatch, 0u, kudwBufferArrayBounds); } //---------------------------------------------------------- /// Destructor //---------------------------------------------------------- DynamicSpriteBatch::~DynamicSpriteBatch() { for(u32 i=0; i<kudwNumBuffers; ++i) { delete mpBatch[i]; } } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // // vie_autotest_linux.cc // #include "vie_autotest_linux.h" #include "vie_autotest_defines.h" #include "vie_autotest_main.h" #include "engine_configurations.h" #include "critical_section_wrapper.h" #include "thread_wrapper.h" ViEAutoTestWindowManager::ViEAutoTestWindowManager() : _hdsp1(NULL), _hdsp2(NULL) { } ViEAutoTestWindowManager::~ViEAutoTestWindowManager() { TerminateWindows(); } void* ViEAutoTestWindowManager::GetWindow1() { return (void*) _hwnd1; } void* ViEAutoTestWindowManager::GetWindow2() { return (void*) _hwnd2; } int ViEAutoTestWindowManager::TerminateWindows() { if (_hwnd1) { ViEDestroyWindow(&_hwnd1, _hdsp1); } if (_hwnd2) { ViEDestroyWindow(&_hwnd2, _hdsp2); } return 0; } int ViEAutoTestWindowManager::CreateWindows(AutoTestRect window1Size, AutoTestRect window2Size, void* window1Title, void* window2Title) { ViECreateWindow(&_hwnd1, &_hdsp1, window1Size.origin.x, window1Size.origin.y, window1Size.size.width, window1Size.size.height, (char*) window1Title); ViECreateWindow(&_hwnd2, &_hdsp2, window2Size.origin.x, window2Size.origin.y, window2Size.size.width, window2Size.size.height, (char*) window2Title); return 0; } int ViEAutoTestWindowManager::ViECreateWindow(Window *outWindow, Display **outDisplay, int xpos, int ypos, int width, int height, char* title) { int screen; XEvent evnt; XSetWindowAttributes xswa; // window attribute struct XVisualInfo vinfo; // screen visual info struct unsigned long mask; // attribute mask // get connection handle to xserver Display* _display = XOpenDisplay(NULL); // get screen number screen = DefaultScreen(_display); // put desired visual info for the screen in vinfo // TODO: more display settings should be allowed if (XMatchVisualInfo(_display, screen, 24, TrueColor, &vinfo) != 0) { //printf( "Screen visual info match!\n" ); } // set window attributes xswa.colormap = XCreateColormap(_display, DefaultRootWindow(_display), vinfo.visual, AllocNone); xswa.event_mask = StructureNotifyMask | ExposureMask; xswa.background_pixel = 0; xswa.border_pixel = 0; // value mask for attributes mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; Window _window = XCreateWindow(_display, DefaultRootWindow(_display), xpos, ypos, width, height, 0, vinfo.depth, InputOutput, vinfo.visual, mask, &xswa); // Set window name XStoreName(_display, _window, title); XSetIconName(_display, _window, title); // make x report events for mask XSelectInput(_display, _window, StructureNotifyMask); // map the window to the display XMapWindow(_display, _window); // wait for map event do { XNextEvent(_display, &evnt); } while (evnt.type != MapNotify || evnt.xmap.event != _window); *outWindow = _window; *outDisplay = _display; return 0; } int ViEAutoTestWindowManager::ViEDestroyWindow(Window *window, Display *display) { XUnmapWindow(display, *window); XDestroyWindow(display, *window); XSync(display, false); return 0; } bool ViEAutoTestWindowManager::SetTopmostWindow() { return 0; } int main() { ViEAutoTestMain autoTest; autoTest.UseAnswerFile("answers.txt"); return autoTest.BeginOSIndependentTesting(); } <commit_msg>Quick fix so ViE autotest doesn't terminate Linux windows twice on exit.<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // // vie_autotest_linux.cc // #include "vie_autotest_linux.h" #include "vie_autotest_defines.h" #include "vie_autotest_main.h" #include "engine_configurations.h" #include "critical_section_wrapper.h" #include "thread_wrapper.h" ViEAutoTestWindowManager::ViEAutoTestWindowManager() : _hdsp1(NULL), _hdsp2(NULL) { } ViEAutoTestWindowManager::~ViEAutoTestWindowManager() { TerminateWindows(); } void* ViEAutoTestWindowManager::GetWindow1() { return (void*) _hwnd1; } void* ViEAutoTestWindowManager::GetWindow2() { return (void*) _hwnd2; } int ViEAutoTestWindowManager::TerminateWindows() { if (_hdsp1) { ViEDestroyWindow(&_hwnd1, _hdsp1); _hdsp1 = NULL; } if (_hdsp2) { ViEDestroyWindow(&_hwnd2, _hdsp2); _hdsp2 = NULL; } return 0; } int ViEAutoTestWindowManager::CreateWindows(AutoTestRect window1Size, AutoTestRect window2Size, void* window1Title, void* window2Title) { ViECreateWindow(&_hwnd1, &_hdsp1, window1Size.origin.x, window1Size.origin.y, window1Size.size.width, window1Size.size.height, (char*) window1Title); ViECreateWindow(&_hwnd2, &_hdsp2, window2Size.origin.x, window2Size.origin.y, window2Size.size.width, window2Size.size.height, (char*) window2Title); return 0; } int ViEAutoTestWindowManager::ViECreateWindow(Window *outWindow, Display **outDisplay, int xpos, int ypos, int width, int height, char* title) { int screen; XEvent evnt; XSetWindowAttributes xswa; // window attribute struct XVisualInfo vinfo; // screen visual info struct unsigned long mask; // attribute mask // get connection handle to xserver Display* _display = XOpenDisplay(NULL); // get screen number screen = DefaultScreen(_display); // put desired visual info for the screen in vinfo // TODO: more display settings should be allowed if (XMatchVisualInfo(_display, screen, 24, TrueColor, &vinfo) != 0) { //printf( "Screen visual info match!\n" ); } // set window attributes xswa.colormap = XCreateColormap(_display, DefaultRootWindow(_display), vinfo.visual, AllocNone); xswa.event_mask = StructureNotifyMask | ExposureMask; xswa.background_pixel = 0; xswa.border_pixel = 0; // value mask for attributes mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; Window _window = XCreateWindow(_display, DefaultRootWindow(_display), xpos, ypos, width, height, 0, vinfo.depth, InputOutput, vinfo.visual, mask, &xswa); // Set window name XStoreName(_display, _window, title); XSetIconName(_display, _window, title); // make x report events for mask XSelectInput(_display, _window, StructureNotifyMask); // map the window to the display XMapWindow(_display, _window); // wait for map event do { XNextEvent(_display, &evnt); } while (evnt.type != MapNotify || evnt.xmap.event != _window); *outWindow = _window; *outDisplay = _display; return 0; } int ViEAutoTestWindowManager::ViEDestroyWindow(Window *window, Display *display) { XUnmapWindow(display, *window); XDestroyWindow(display, *window); XSync(display, false); return 0; } bool ViEAutoTestWindowManager::SetTopmostWindow() { return 0; } int main() { ViEAutoTestMain autoTest; autoTest.UseAnswerFile("answers.txt"); return autoTest.BeginOSIndependentTesting(); } <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "shared_operation_throttler.h" #include <condition_variable> #include <cassert> #include <functional> #include <mutex> namespace vespalib { namespace { class NoLimitsOperationThrottler final : public SharedOperationThrottler { public: ~NoLimitsOperationThrottler() override = default; Token blocking_acquire_one() noexcept override { return Token(this, TokenCtorTag{}); } Token blocking_acquire_one(vespalib::duration) noexcept override { return Token(this, TokenCtorTag{}); } Token try_acquire_one() noexcept override { return Token(this, TokenCtorTag{}); } uint32_t current_window_size() const noexcept override { return 0; } uint32_t waiting_threads() const noexcept override { return 0; } private: void release_one() noexcept override { /* no-op */ } }; /** * Effectively a 1-1 transplant of the MessageBus DynamicThrottlePolicy, but * without an underlying StaticThrottlePolicy and with no need for individual * MessageBus Message/Reply objects. * * Please keep the underlying algorithm in sync with the Java implementation, * as that is considered the source of truth. For descriptions of the various * parameters, also see the Java code. */ class DynamicThrottlePolicy { std::function<steady_time()> _time_provider; uint32_t _num_sent; uint32_t _num_ok; double _resize_rate; uint64_t _resize_time; uint64_t _time_of_last_message; uint64_t _idle_time_period; double _efficiency_threshold; double _window_size_increment; double _window_size; double _max_window_size; double _min_window_size; double _decrement_factor; double _window_size_backoff; double _weight; double _local_max_throughput; public: DynamicThrottlePolicy(const SharedOperationThrottler::DynamicThrottleParams& params, std::function<steady_time()> time_provider); void set_window_size_increment(double window_size_increment) noexcept; void set_window_size_backoff(double window_size_backoff) noexcept; void set_resize_rate(double resize_rate) noexcept; void set_max_window_size(double max_size) noexcept; void set_min_window_size(double min_size) noexcept; void set_window_size_decrement_factor(double decrement_factor) noexcept; [[nodiscard]] uint32_t current_window_size() const noexcept { return static_cast<uint32_t>(_window_size); } [[nodiscard]] bool has_spare_capacity(uint32_t pending_count) noexcept; void process_request() noexcept; void process_response(bool success) noexcept; private: [[nodiscard]] uint64_t current_time_as_millis() noexcept { return count_ms(_time_provider().time_since_epoch()); } }; DynamicThrottlePolicy::DynamicThrottlePolicy(const SharedOperationThrottler::DynamicThrottleParams& params, std::function<steady_time()> time_provider) : _time_provider(std::move(time_provider)), _num_sent(0), _num_ok(0), _resize_rate(3.0), _resize_time(0), _time_of_last_message(current_time_as_millis()), _idle_time_period(60000), _efficiency_threshold(1), _window_size_increment(20), _window_size(_window_size_increment), _max_window_size(INT_MAX), _min_window_size(_window_size_increment), _decrement_factor(2.0), _window_size_backoff(0.9), _weight(1), _local_max_throughput(0) { // We use setters for convenience, since setting one parameter may imply setting others, // based on it, and there's frequently min/max capping of values. set_window_size_increment(params.window_size_increment); set_min_window_size(params.min_window_size); set_max_window_size(params.max_window_size); set_resize_rate(params.resize_rate); set_window_size_decrement_factor(params.window_size_decrement_factor); set_window_size_backoff(params.window_size_backoff); } void DynamicThrottlePolicy::set_window_size_increment(double window_size_increment) noexcept { _window_size_increment = window_size_increment; _window_size = std::max(_window_size, _window_size_increment); } void DynamicThrottlePolicy::set_window_size_backoff(double window_size_backoff) noexcept { _window_size_backoff = std::max(0.0, std::min(1.0, window_size_backoff)); } void DynamicThrottlePolicy::set_resize_rate(double resize_rate) noexcept { _resize_rate = std::max(2.0, resize_rate); } void DynamicThrottlePolicy::set_max_window_size(double max_size) noexcept { _max_window_size = max_size; } void DynamicThrottlePolicy::set_min_window_size(double min_size) noexcept { _min_window_size = min_size; _window_size = std::max(_min_window_size, _window_size_increment); } void DynamicThrottlePolicy::set_window_size_decrement_factor(double decrement_factor) noexcept { _decrement_factor = decrement_factor; } bool DynamicThrottlePolicy::has_spare_capacity(uint32_t pending_count) noexcept { const uint64_t time = current_time_as_millis(); if ((time - _time_of_last_message) > _idle_time_period) { _window_size = std::max(_min_window_size, std::min(_window_size, pending_count + _window_size_increment)); } _time_of_last_message = time; const auto window_size_floored = static_cast<uint32_t>(_window_size); // Use floating point window sizes, so the algorithm sees the difference between 1.1 and 1.9 window size. const bool carry = _num_sent < ((_window_size * _resize_rate) * (_window_size - window_size_floored)); return pending_count < (window_size_floored + (carry ? 1 : 0)); } void DynamicThrottlePolicy::process_request() noexcept { if (++_num_sent < (_window_size * _resize_rate)) { return; } const uint64_t time = current_time_as_millis(); const double elapsed = time - _resize_time; _resize_time = time; const double throughput = _num_ok / elapsed; _num_sent = 0; _num_ok = 0; if (throughput > _local_max_throughput) { _local_max_throughput = throughput; _window_size += _weight * _window_size_increment; } else { // scale up/down throughput for comparing to window size double period = 1; while ((throughput * (period / _window_size)) < 2) { period *= 10; } while ((throughput * (period / _window_size)) > 2) { period *= 0.1; } const double efficiency = throughput * (period / _window_size); if (efficiency < _efficiency_threshold) { _window_size = std::min(_window_size * _window_size_backoff, _window_size - _decrement_factor * _window_size_increment); _local_max_throughput = 0; } else { _window_size += _weight * _window_size_increment; } } _window_size = std::max(_min_window_size, _window_size); _window_size = std::min(_max_window_size, _window_size); } void DynamicThrottlePolicy::process_response(bool success) noexcept { if (success) { ++_num_ok; } } class DynamicOperationThrottler final : public SharedOperationThrottler { mutable std::mutex _mutex; std::condition_variable _cond; DynamicThrottlePolicy _throttle_policy; uint32_t _pending_ops; uint32_t _waiting_threads; public: DynamicOperationThrottler(const DynamicThrottleParams& params, std::function<steady_time()> time_provider); ~DynamicOperationThrottler() override; Token blocking_acquire_one() noexcept override; Token blocking_acquire_one(vespalib::duration timeout) noexcept override; Token try_acquire_one() noexcept override; uint32_t current_window_size() const noexcept override; uint32_t waiting_threads() const noexcept override; private: void release_one() noexcept override; // Non-const since actually checking the send window of a dynamic throttler might change // it if enough time has passed. [[nodiscard]] bool has_spare_capacity_in_active_window() noexcept; void add_one_to_active_window_size() noexcept; void subtract_one_from_active_window_size() noexcept; }; DynamicOperationThrottler::DynamicOperationThrottler(const DynamicThrottleParams& params, std::function<steady_time()> time_provider) : _mutex(), _cond(), _throttle_policy(params, std::move(time_provider)), _pending_ops(0), _waiting_threads(0) { } DynamicOperationThrottler::~DynamicOperationThrottler() = default; bool DynamicOperationThrottler::has_spare_capacity_in_active_window() noexcept { return _throttle_policy.has_spare_capacity(_pending_ops); } void DynamicOperationThrottler::add_one_to_active_window_size() noexcept { _throttle_policy.process_request(); ++_pending_ops; } void DynamicOperationThrottler::subtract_one_from_active_window_size() noexcept { _throttle_policy.process_response(true); // TODO support failure push-back assert(_pending_ops > 0); --_pending_ops; } DynamicOperationThrottler::Token DynamicOperationThrottler::blocking_acquire_one() noexcept { std::unique_lock lock(_mutex); if (!has_spare_capacity_in_active_window()) { ++_waiting_threads; _cond.wait(lock, [&] { return has_spare_capacity_in_active_window(); }); --_waiting_threads; } add_one_to_active_window_size(); return Token(this, TokenCtorTag{}); } DynamicOperationThrottler::Token DynamicOperationThrottler::blocking_acquire_one(vespalib::duration timeout) noexcept { std::unique_lock lock(_mutex); if (!has_spare_capacity_in_active_window()) { ++_waiting_threads; const bool accepted = _cond.wait_for(lock, timeout, [&] { return has_spare_capacity_in_active_window(); }); --_waiting_threads; if (!accepted) { return Token(); } } add_one_to_active_window_size(); return Token(this, TokenCtorTag{}); } DynamicOperationThrottler::Token DynamicOperationThrottler::try_acquire_one() noexcept { std::unique_lock lock(_mutex); if (!has_spare_capacity_in_active_window()) { return Token(); } add_one_to_active_window_size(); return Token(this, TokenCtorTag{}); } void DynamicOperationThrottler::release_one() noexcept { std::unique_lock lock(_mutex); subtract_one_from_active_window_size(); // Only wake up a waiting thread if doing so would possibly result in success. if ((_waiting_threads > 0) && has_spare_capacity_in_active_window()) { lock.unlock(); _cond.notify_one(); } } uint32_t DynamicOperationThrottler::current_window_size() const noexcept { std::unique_lock lock(_mutex); return _throttle_policy.current_window_size(); } uint32_t DynamicOperationThrottler::waiting_threads() const noexcept { std::unique_lock lock(_mutex); return _waiting_threads; } } // anonymous namespace std::unique_ptr<SharedOperationThrottler> SharedOperationThrottler::make_unlimited_throttler() { return std::make_unique<NoLimitsOperationThrottler>(); } std::unique_ptr<SharedOperationThrottler> SharedOperationThrottler::make_dynamic_throttler(const DynamicThrottleParams& params) { return std::make_unique<DynamicOperationThrottler>(params, []() noexcept { return steady_clock::now(); }); } std::unique_ptr<SharedOperationThrottler> SharedOperationThrottler::make_dynamic_throttler(const DynamicThrottleParams& params, std::function<steady_time()> time_provider) { return std::make_unique<DynamicOperationThrottler>(params, std::move(time_provider)); } DynamicOperationThrottler::Token::~Token() { if (_throttler) { _throttler->release_one(); } } void DynamicOperationThrottler::Token::reset() noexcept { if (_throttler) { _throttler->release_one(); _throttler = nullptr; } } DynamicOperationThrottler::Token& DynamicOperationThrottler::Token::operator=(Token&& rhs) noexcept { reset(); _throttler = rhs._throttler; rhs._throttler = nullptr; return *this; } } <commit_msg>Add reference to Java throttle policy file<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "shared_operation_throttler.h" #include <condition_variable> #include <cassert> #include <functional> #include <mutex> namespace vespalib { namespace { class NoLimitsOperationThrottler final : public SharedOperationThrottler { public: ~NoLimitsOperationThrottler() override = default; Token blocking_acquire_one() noexcept override { return Token(this, TokenCtorTag{}); } Token blocking_acquire_one(vespalib::duration) noexcept override { return Token(this, TokenCtorTag{}); } Token try_acquire_one() noexcept override { return Token(this, TokenCtorTag{}); } uint32_t current_window_size() const noexcept override { return 0; } uint32_t waiting_threads() const noexcept override { return 0; } private: void release_one() noexcept override { /* no-op */ } }; /** * Effectively a 1-1 transplant of the MessageBus DynamicThrottlePolicy, but * without an underlying StaticThrottlePolicy and with no need for individual * MessageBus Message/Reply objects. * * Please keep the underlying algorithm in sync with the Java implementation, * as that is considered the source of truth. For descriptions of the various * parameters, also see the Java code: * messagebus/src/main/java/com/yahoo/messagebus/DynamicThrottlePolicy.java */ class DynamicThrottlePolicy { std::function<steady_time()> _time_provider; uint32_t _num_sent; uint32_t _num_ok; double _resize_rate; uint64_t _resize_time; uint64_t _time_of_last_message; uint64_t _idle_time_period; double _efficiency_threshold; double _window_size_increment; double _window_size; double _max_window_size; double _min_window_size; double _decrement_factor; double _window_size_backoff; double _weight; double _local_max_throughput; public: DynamicThrottlePolicy(const SharedOperationThrottler::DynamicThrottleParams& params, std::function<steady_time()> time_provider); void set_window_size_increment(double window_size_increment) noexcept; void set_window_size_backoff(double window_size_backoff) noexcept; void set_resize_rate(double resize_rate) noexcept; void set_max_window_size(double max_size) noexcept; void set_min_window_size(double min_size) noexcept; void set_window_size_decrement_factor(double decrement_factor) noexcept; [[nodiscard]] uint32_t current_window_size() const noexcept { return static_cast<uint32_t>(_window_size); } [[nodiscard]] bool has_spare_capacity(uint32_t pending_count) noexcept; void process_request() noexcept; void process_response(bool success) noexcept; private: [[nodiscard]] uint64_t current_time_as_millis() noexcept { return count_ms(_time_provider().time_since_epoch()); } }; DynamicThrottlePolicy::DynamicThrottlePolicy(const SharedOperationThrottler::DynamicThrottleParams& params, std::function<steady_time()> time_provider) : _time_provider(std::move(time_provider)), _num_sent(0), _num_ok(0), _resize_rate(3.0), _resize_time(0), _time_of_last_message(current_time_as_millis()), _idle_time_period(60000), _efficiency_threshold(1), _window_size_increment(20), _window_size(_window_size_increment), _max_window_size(INT_MAX), _min_window_size(_window_size_increment), _decrement_factor(2.0), _window_size_backoff(0.9), _weight(1), _local_max_throughput(0) { // We use setters for convenience, since setting one parameter may imply setting others, // based on it, and there's frequently min/max capping of values. set_window_size_increment(params.window_size_increment); set_min_window_size(params.min_window_size); set_max_window_size(params.max_window_size); set_resize_rate(params.resize_rate); set_window_size_decrement_factor(params.window_size_decrement_factor); set_window_size_backoff(params.window_size_backoff); } void DynamicThrottlePolicy::set_window_size_increment(double window_size_increment) noexcept { _window_size_increment = window_size_increment; _window_size = std::max(_window_size, _window_size_increment); } void DynamicThrottlePolicy::set_window_size_backoff(double window_size_backoff) noexcept { _window_size_backoff = std::max(0.0, std::min(1.0, window_size_backoff)); } void DynamicThrottlePolicy::set_resize_rate(double resize_rate) noexcept { _resize_rate = std::max(2.0, resize_rate); } void DynamicThrottlePolicy::set_max_window_size(double max_size) noexcept { _max_window_size = max_size; } void DynamicThrottlePolicy::set_min_window_size(double min_size) noexcept { _min_window_size = min_size; _window_size = std::max(_min_window_size, _window_size_increment); } void DynamicThrottlePolicy::set_window_size_decrement_factor(double decrement_factor) noexcept { _decrement_factor = decrement_factor; } bool DynamicThrottlePolicy::has_spare_capacity(uint32_t pending_count) noexcept { const uint64_t time = current_time_as_millis(); if ((time - _time_of_last_message) > _idle_time_period) { _window_size = std::max(_min_window_size, std::min(_window_size, pending_count + _window_size_increment)); } _time_of_last_message = time; const auto window_size_floored = static_cast<uint32_t>(_window_size); // Use floating point window sizes, so the algorithm sees the difference between 1.1 and 1.9 window size. const bool carry = _num_sent < ((_window_size * _resize_rate) * (_window_size - window_size_floored)); return pending_count < (window_size_floored + (carry ? 1 : 0)); } void DynamicThrottlePolicy::process_request() noexcept { if (++_num_sent < (_window_size * _resize_rate)) { return; } const uint64_t time = current_time_as_millis(); const double elapsed = time - _resize_time; _resize_time = time; const double throughput = _num_ok / elapsed; _num_sent = 0; _num_ok = 0; if (throughput > _local_max_throughput) { _local_max_throughput = throughput; _window_size += _weight * _window_size_increment; } else { // scale up/down throughput for comparing to window size double period = 1; while ((throughput * (period / _window_size)) < 2) { period *= 10; } while ((throughput * (period / _window_size)) > 2) { period *= 0.1; } const double efficiency = throughput * (period / _window_size); if (efficiency < _efficiency_threshold) { _window_size = std::min(_window_size * _window_size_backoff, _window_size - _decrement_factor * _window_size_increment); _local_max_throughput = 0; } else { _window_size += _weight * _window_size_increment; } } _window_size = std::max(_min_window_size, _window_size); _window_size = std::min(_max_window_size, _window_size); } void DynamicThrottlePolicy::process_response(bool success) noexcept { if (success) { ++_num_ok; } } class DynamicOperationThrottler final : public SharedOperationThrottler { mutable std::mutex _mutex; std::condition_variable _cond; DynamicThrottlePolicy _throttle_policy; uint32_t _pending_ops; uint32_t _waiting_threads; public: DynamicOperationThrottler(const DynamicThrottleParams& params, std::function<steady_time()> time_provider); ~DynamicOperationThrottler() override; Token blocking_acquire_one() noexcept override; Token blocking_acquire_one(vespalib::duration timeout) noexcept override; Token try_acquire_one() noexcept override; uint32_t current_window_size() const noexcept override; uint32_t waiting_threads() const noexcept override; private: void release_one() noexcept override; // Non-const since actually checking the send window of a dynamic throttler might change // it if enough time has passed. [[nodiscard]] bool has_spare_capacity_in_active_window() noexcept; void add_one_to_active_window_size() noexcept; void subtract_one_from_active_window_size() noexcept; }; DynamicOperationThrottler::DynamicOperationThrottler(const DynamicThrottleParams& params, std::function<steady_time()> time_provider) : _mutex(), _cond(), _throttle_policy(params, std::move(time_provider)), _pending_ops(0), _waiting_threads(0) { } DynamicOperationThrottler::~DynamicOperationThrottler() = default; bool DynamicOperationThrottler::has_spare_capacity_in_active_window() noexcept { return _throttle_policy.has_spare_capacity(_pending_ops); } void DynamicOperationThrottler::add_one_to_active_window_size() noexcept { _throttle_policy.process_request(); ++_pending_ops; } void DynamicOperationThrottler::subtract_one_from_active_window_size() noexcept { _throttle_policy.process_response(true); // TODO support failure push-back assert(_pending_ops > 0); --_pending_ops; } DynamicOperationThrottler::Token DynamicOperationThrottler::blocking_acquire_one() noexcept { std::unique_lock lock(_mutex); if (!has_spare_capacity_in_active_window()) { ++_waiting_threads; _cond.wait(lock, [&] { return has_spare_capacity_in_active_window(); }); --_waiting_threads; } add_one_to_active_window_size(); return Token(this, TokenCtorTag{}); } DynamicOperationThrottler::Token DynamicOperationThrottler::blocking_acquire_one(vespalib::duration timeout) noexcept { std::unique_lock lock(_mutex); if (!has_spare_capacity_in_active_window()) { ++_waiting_threads; const bool accepted = _cond.wait_for(lock, timeout, [&] { return has_spare_capacity_in_active_window(); }); --_waiting_threads; if (!accepted) { return Token(); } } add_one_to_active_window_size(); return Token(this, TokenCtorTag{}); } DynamicOperationThrottler::Token DynamicOperationThrottler::try_acquire_one() noexcept { std::unique_lock lock(_mutex); if (!has_spare_capacity_in_active_window()) { return Token(); } add_one_to_active_window_size(); return Token(this, TokenCtorTag{}); } void DynamicOperationThrottler::release_one() noexcept { std::unique_lock lock(_mutex); subtract_one_from_active_window_size(); // Only wake up a waiting thread if doing so would possibly result in success. if ((_waiting_threads > 0) && has_spare_capacity_in_active_window()) { lock.unlock(); _cond.notify_one(); } } uint32_t DynamicOperationThrottler::current_window_size() const noexcept { std::unique_lock lock(_mutex); return _throttle_policy.current_window_size(); } uint32_t DynamicOperationThrottler::waiting_threads() const noexcept { std::unique_lock lock(_mutex); return _waiting_threads; } } // anonymous namespace std::unique_ptr<SharedOperationThrottler> SharedOperationThrottler::make_unlimited_throttler() { return std::make_unique<NoLimitsOperationThrottler>(); } std::unique_ptr<SharedOperationThrottler> SharedOperationThrottler::make_dynamic_throttler(const DynamicThrottleParams& params) { return std::make_unique<DynamicOperationThrottler>(params, []() noexcept { return steady_clock::now(); }); } std::unique_ptr<SharedOperationThrottler> SharedOperationThrottler::make_dynamic_throttler(const DynamicThrottleParams& params, std::function<steady_time()> time_provider) { return std::make_unique<DynamicOperationThrottler>(params, std::move(time_provider)); } DynamicOperationThrottler::Token::~Token() { if (_throttler) { _throttler->release_one(); } } void DynamicOperationThrottler::Token::reset() noexcept { if (_throttler) { _throttler->release_one(); _throttler = nullptr; } } DynamicOperationThrottler::Token& DynamicOperationThrottler::Token::operator=(Token&& rhs) noexcept { reset(); _throttler = rhs._throttler; rhs._throttler = nullptr; return *this; } } <|endoftext|>
<commit_before>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "YamlSubstIstream.hxx" #include "SubstIstream.hxx" #include "FailIstream.hxx" #include "UnusedPtr.hxx" #include "pool/pool.hxx" #include "util/RuntimeError.hxx" #include "util/StringView.hxx" #include <yaml-cpp/node/parse.h> #include <yaml-cpp/node/node.h> #include <yaml-cpp/node/iterator.h> #include <yaml-cpp/node/impl.h> static SubstTree LoadYamlMap(struct pool &pool, const YAML::Node &node) noexcept { assert(node.IsMap()); SubstTree tree; for (const auto &i : node) { const auto name = "{{" + i.first.as<std::string>() + "}}"; const auto value = i.second.as<std::string>(); tree.Add(pool, p_strndup(&pool, name.data(), name.length()), {p_strndup(&pool, value.data(), value.length()), value.length()}); } return tree; } static SubstTree LoadYamlFile(struct pool &pool, const char *path) { const auto root = YAML::LoadFile(path); if (!root.IsMap()) throw std::runtime_error("File '%s' is not a YAML map"); return LoadYamlMap(pool, root); } UnusedIstreamPtr NewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input, const char *yaml_file) { return istream_subst_new(&pool, std::move(input), LoadYamlFile(pool, yaml_file)); } <commit_msg>istream/YamlSubst: ignore non-scalars<commit_after>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "YamlSubstIstream.hxx" #include "SubstIstream.hxx" #include "FailIstream.hxx" #include "UnusedPtr.hxx" #include "pool/pool.hxx" #include "util/RuntimeError.hxx" #include "util/StringView.hxx" #include <yaml-cpp/node/parse.h> #include <yaml-cpp/node/node.h> #include <yaml-cpp/node/iterator.h> #include <yaml-cpp/node/impl.h> static SubstTree LoadYamlMap(struct pool &pool, const YAML::Node &node) noexcept { assert(node.IsMap()); SubstTree tree; for (const auto &i : node) { if (!i.first.IsScalar() || !i.second.IsScalar()) continue; const auto name = "{{" + i.first.as<std::string>() + "}}"; const auto value = i.second.as<std::string>(); tree.Add(pool, p_strndup(&pool, name.data(), name.length()), {p_strndup(&pool, value.data(), value.length()), value.length()}); } return tree; } static SubstTree LoadYamlFile(struct pool &pool, const char *path) { const auto root = YAML::LoadFile(path); if (!root.IsMap()) throw std::runtime_error("File '%s' is not a YAML map"); return LoadYamlMap(pool, root); } UnusedIstreamPtr NewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input, const char *yaml_file) { return istream_subst_new(&pool, std::move(input), LoadYamlFile(pool, yaml_file)); } <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <PluginManager/Manager.h> #include <DefaultFramebuffer.h> #include <Mesh.h> #include <Renderer.h> #include <ResourceManager.h> #include <MeshTools/Interleave.h> #include <MeshTools/CompressIndices.h> #include <SceneGraph/Scene.h> #include <SceneGraph/Camera3D.h> #include <SceneGraph/Drawable.h> #include <SceneGraph/MatrixTransformation3D.h> #include <Shaders/Phong.h> #include <Trade/AbstractImporter.h> #include <Trade/MeshData3D.h> #include <Trade/MeshObjectData3D.h> #include <Trade/PhongMaterialData.h> #include <Trade/SceneData.h> #ifndef MAGNUM_TARGET_GLES #include <Platform/GlutApplication.h> #else #include <Platform/XEglApplication.h> #endif #include "configure.h" namespace Magnum { namespace Examples { typedef ResourceManager<Trade::AbstractImporter, Trade::PhongMaterialData, Shaders::Phong, Mesh, Buffer> ViewerResourceManager; typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D; typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D; class ViewerExample: public Platform::Application { public: explicit ViewerExample(const Arguments& arguments); protected: void viewportEvent(const Vector2i& size) override; void drawEvent() override; void mousePressEvent(MouseEvent& event) override; void mouseReleaseEvent(MouseEvent& event) override; void mouseMoveEvent(MouseMoveEvent& event) override; private: Vector3 positionOnSphere(const Vector2i& _position) const; void addObject(Trade::AbstractImporter* colladaImporter, Object3D* parent, std::size_t objectId); ViewerResourceManager resourceManager; Scene3D scene; Object3D *o, *cameraObject; SceneGraph::Camera3D* camera; SceneGraph::DrawableGroup3D drawables; Vector3 previousPosition; }; class MeshLoader: public AbstractResourceLoader<Mesh> { public: explicit MeshLoader(); private: void doLoad(ResourceKey key) override; Resource<Trade::AbstractImporter> importer; std::unordered_map<ResourceKey, std::size_t> keyMap; }; class MaterialLoader: public AbstractResourceLoader<Trade::PhongMaterialData> { public: explicit MaterialLoader(); private: void doLoad(ResourceKey key) override; Resource<Trade::AbstractImporter> importer; std::unordered_map<ResourceKey, std::size_t> keyMap; }; class ViewedObject: public Object3D, SceneGraph::Drawable3D { public: ViewedObject(ResourceKey meshKey, ResourceKey materialKey, Object3D* parent, SceneGraph::DrawableGroup3D* group); void draw(const Matrix4& transformationMatrix, SceneGraph::AbstractCamera3D* camera) override; private: Resource<Mesh> mesh; Resource<Shaders::Phong> shader; Vector3 ambientColor, diffuseColor, specularColor; Float shininess; }; ViewerExample::ViewerExample(const Arguments& arguments): Platform::Application(arguments, Configuration().setTitle("Magnum Viewer")) { if(arguments.argc != 2) { Debug() << "Usage:" << arguments.argv[0] << "file.dae"; std::exit(0); } /* Instance ColladaImporter plugin */ PluginManager::Manager<Trade::AbstractImporter> manager(MAGNUM_PLUGINS_IMPORTER_DIR); if(manager.load("ColladaImporter") != PluginManager::LoadState::Loaded) { Error() << "Could not load ColladaImporter plugin"; std::exit(1); } Trade::AbstractImporter* colladaImporter = manager.instance("ColladaImporter"); if(colladaImporter) resourceManager.set("importer", colladaImporter, ResourceDataState::Final, ResourcePolicy::Manual); else { Error() << "Could not instance ColladaImporter plugin"; std::exit(2); } /* Every scene needs a camera */ (cameraObject = new Object3D(&scene)) ->translate(Vector3::zAxis(5)); (camera = new SceneGraph::Camera3D(cameraObject)) ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) ->setPerspective(35.0_degf, 1.0f, 0.001f, 100); Renderer::setFeature(Renderer::Feature::DepthTest, true); Renderer::setFeature(Renderer::Feature::FaceCulling, true); Debug() << "Opening file" << arguments.argv[1]; /* Load file */ if(!colladaImporter->openFile(arguments.argv[1])) { std::exit(4); } if(!colladaImporter->sceneCount()) { std::exit(5); } /* Resource loaders */ auto meshLoader = new MeshLoader; auto materialLoader = new MaterialLoader; resourceManager.setLoader(meshLoader)->setLoader(materialLoader); /* Phong shader instance */ resourceManager.set("color", new Shaders::Phong); /* Fallback mesh for objects with no mesh */ resourceManager.setFallback(new Mesh); /* Fallback material for objects with no material */ auto material = new Trade::PhongMaterialData({}, 50.0f); material->ambientColor() = {0.0f, 0.0f, 0.0f}; material->diffuseColor() = {0.9f, 0.9f, 0.9f}; material->specularColor() = {1.0f, 1.0f, 1.0f}; resourceManager.setFallback(material); Debug() << "Adding default scene" << colladaImporter->sceneName(colladaImporter->defaultScene()); /* Default object, parent of all (for manipulation) */ o = new Object3D(&scene); /* Load the scene */ Trade::SceneData* scene = colladaImporter->scene(colladaImporter->defaultScene()); /* Add all children */ for(UnsignedInt objectId: scene->children3D()) addObject(colladaImporter, o, objectId); /* Importer, materials and loaders are not needed anymore */ resourceManager.setFallback<Trade::PhongMaterialData>(nullptr) ->setLoader<Mesh>(nullptr) ->setLoader<Trade::PhongMaterialData>(nullptr) ->clear<Trade::PhongMaterialData>() ->clear<Trade::AbstractImporter>(); Debug() << "Imported" << meshLoader->loadedCount() << "meshes and" << materialLoader->loadedCount() << "materials," << meshLoader->notFoundCount() << "meshes and" << materialLoader->notFoundCount() << "materials weren't found."; } void ViewerExample::viewportEvent(const Vector2i& size) { defaultFramebuffer.setViewport({{}, size}); camera->setViewport(size); } void ViewerExample::drawEvent() { defaultFramebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth); camera->draw(drawables); swapBuffers(); } void ViewerExample::mousePressEvent(MouseEvent& event) { switch(event.button()) { case MouseEvent::Button::Left: previousPosition = positionOnSphere(event.position()); break; case MouseEvent::Button::WheelUp: case MouseEvent::Button::WheelDown: { /* Distance between origin and near camera clipping plane */ Float distance = cameraObject->transformation().translation().z()-0-camera->near(); /* Move 15% of the distance back or forward */ distance *= 1 - (event.button() == MouseEvent::Button::WheelUp ? 1/0.85f : 0.85f); cameraObject->translate(Vector3::zAxis(distance), SceneGraph::TransformationType::Global); redraw(); break; } default: ; } } void ViewerExample::mouseReleaseEvent(MouseEvent& event) { if(event.button() == MouseEvent::Button::Left) previousPosition = Vector3(); } void ViewerExample::mouseMoveEvent(MouseMoveEvent& event) { Vector3 currentPosition = positionOnSphere(event.position()); Vector3 axis = Vector3::cross(previousPosition, currentPosition); if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return; o->rotate(Vector3::angle(previousPosition, currentPosition), axis.normalized()); previousPosition = currentPosition; redraw(); } Vector3 ViewerExample::positionOnSphere(const Vector2i& _position) const { Vector2 position = Vector2(_position*2)/camera->viewport() - Vector2(1.0f); Float length = position.length(); Vector3 result(length > 1.0f ? Vector3(position, 0.0f) : Vector3(position, 1.0f - length)); result.y() *= -1.0f; return result.normalized(); } void ViewerExample::addObject(Trade::AbstractImporter* colladaImporter, Object3D* parent, std::size_t objectId) { Trade::ObjectData3D* object = colladaImporter->object3D(objectId); Debug() << "Importing object" << colladaImporter->object3DName(objectId); /* Only meshes for now */ if(object->instanceType() == Trade::ObjectData3D::InstanceType::Mesh) { const auto materialName = colladaImporter->materialName(static_cast<Trade::MeshObjectData3D*>(object)->material()); const ResourceKey materialKey(materialName); /* Decide what object to add based on material type */ Resource<Trade::PhongMaterialData> material = resourceManager.get<Trade::PhongMaterialData>(materialKey); /* Color-only material */ if(!material->flags()) (new ViewedObject(colladaImporter->mesh3DName(object->instance()), materialKey, parent, &drawables)) ->setTransformation(object->transformation()); /* No other material types are supported yet */ else Error() << "Texture combination of material" << materialName << "is not supported"; } /* Recursively add children */ for(std::size_t id: object->children()) addObject(colladaImporter, o, id); } MeshLoader::MeshLoader(): importer(ViewerResourceManager::instance()->get<Trade::AbstractImporter>("importer")) { /* Fill key->name map */ for(UnsignedInt i = 0; i != importer->mesh3DCount(); ++i) keyMap.emplace(importer->mesh3DName(i), i); } void MeshLoader::doLoad(const ResourceKey key) { const UnsignedInt id = keyMap.at(key); Debug() << "Importing mesh" << importer->mesh3DName(id) << "..."; Trade::MeshData3D* data = importer->mesh3D(id); if(!data || !data->isIndexed() || !data->positionArrayCount() || !data->normalArrayCount() || data->primitive() != Mesh::Primitive::Triangles) { delete data; setNotFound(key); return; } /* Fill mesh data */ auto mesh = new Mesh; auto buffer = new Buffer; auto indexBuffer = new Buffer; MeshTools::interleave(mesh, buffer, Buffer::Usage::StaticDraw, data->positions(0), data->normals(0)); MeshTools::compressIndices(mesh, indexBuffer, Buffer::Usage::StaticDraw, data->indices()); mesh->addInterleavedVertexBuffer(buffer, 0, Shaders::Phong::Position(), Shaders::Phong::Normal()) ->setPrimitive(data->primitive()); /* Save things */ ViewerResourceManager::instance()->set(importer->mesh3DName(id) + "-vertices", buffer); ViewerResourceManager::instance()->set(importer->mesh3DName(id) + "-indices", indexBuffer); set(key, mesh); delete data; } MaterialLoader::MaterialLoader(): importer(ViewerResourceManager::instance()->get<Trade::AbstractImporter>("importer")) { /* Fill key->name map */ for(UnsignedInt i = 0; i != importer->materialCount(); ++i) keyMap.emplace(importer->materialName(i), i); } void MaterialLoader::doLoad(const ResourceKey key) { const UnsignedInt id = keyMap.at(key); Debug() << "Importing material" << importer->materialName(id); auto material = importer->material(id); if(material && material->type() == Trade::AbstractMaterialData::Type::Phong) set(key, static_cast<Trade::PhongMaterialData*>(material), ResourceDataState::Final, ResourcePolicy::Manual); else setNotFound(key); } ViewedObject::ViewedObject(const ResourceKey meshKey, const ResourceKey materialKey, Object3D* parent, SceneGraph::DrawableGroup3D* group): Object3D(parent), SceneGraph::Drawable3D(this, group), mesh(ViewerResourceManager::instance()->get<Mesh>(meshKey)), shader(ViewerResourceManager::instance()->get<Shaders::Phong>("color")) { Resource<Trade::PhongMaterialData> material = ViewerResourceManager::instance()->get<Trade::PhongMaterialData>(materialKey); ambientColor = material->ambientColor(); diffuseColor = material->diffuseColor(); specularColor = material->specularColor(); shininess = material->shininess(); } void ViewedObject::draw(const Matrix4& transformationMatrix, SceneGraph::AbstractCamera3D* camera) { shader->setAmbientColor(ambientColor) ->setDiffuseColor(diffuseColor) ->setSpecularColor(specularColor) ->setShininess(shininess) ->setLightPosition({-3.0f, 10.0f, 10.0f}) ->setTransformationMatrix(transformationMatrix) ->setNormalMatrix(transformationMatrix.rotation()) ->setProjectionMatrix(camera->projectionMatrix()) ->use(); mesh->draw(); } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::ViewerExample) <commit_msg>viewer: use `importer` instead of `colladaImporter`.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <PluginManager/Manager.h> #include <DefaultFramebuffer.h> #include <Mesh.h> #include <Renderer.h> #include <ResourceManager.h> #include <MeshTools/Interleave.h> #include <MeshTools/CompressIndices.h> #include <SceneGraph/Scene.h> #include <SceneGraph/Camera3D.h> #include <SceneGraph/Drawable.h> #include <SceneGraph/MatrixTransformation3D.h> #include <Shaders/Phong.h> #include <Trade/AbstractImporter.h> #include <Trade/MeshData3D.h> #include <Trade/MeshObjectData3D.h> #include <Trade/PhongMaterialData.h> #include <Trade/SceneData.h> #ifndef MAGNUM_TARGET_GLES #include <Platform/GlutApplication.h> #else #include <Platform/XEglApplication.h> #endif #include "configure.h" namespace Magnum { namespace Examples { typedef ResourceManager<Trade::AbstractImporter, Trade::PhongMaterialData, Shaders::Phong, Mesh, Buffer> ViewerResourceManager; typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D; typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D; class ViewerExample: public Platform::Application { public: explicit ViewerExample(const Arguments& arguments); protected: void viewportEvent(const Vector2i& size) override; void drawEvent() override; void mousePressEvent(MouseEvent& event) override; void mouseReleaseEvent(MouseEvent& event) override; void mouseMoveEvent(MouseMoveEvent& event) override; private: Vector3 positionOnSphere(const Vector2i& _position) const; void addObject(Trade::AbstractImporter* importer, Object3D* parent, std::size_t objectId); ViewerResourceManager resourceManager; Scene3D scene; Object3D *o, *cameraObject; SceneGraph::Camera3D* camera; SceneGraph::DrawableGroup3D drawables; Vector3 previousPosition; }; class MeshLoader: public AbstractResourceLoader<Mesh> { public: explicit MeshLoader(); private: void doLoad(ResourceKey key) override; Resource<Trade::AbstractImporter> importer; std::unordered_map<ResourceKey, std::size_t> keyMap; }; class MaterialLoader: public AbstractResourceLoader<Trade::PhongMaterialData> { public: explicit MaterialLoader(); private: void doLoad(ResourceKey key) override; Resource<Trade::AbstractImporter> importer; std::unordered_map<ResourceKey, std::size_t> keyMap; }; class ViewedObject: public Object3D, SceneGraph::Drawable3D { public: ViewedObject(ResourceKey meshKey, ResourceKey materialKey, Object3D* parent, SceneGraph::DrawableGroup3D* group); void draw(const Matrix4& transformationMatrix, SceneGraph::AbstractCamera3D* camera) override; private: Resource<Mesh> mesh; Resource<Shaders::Phong> shader; Vector3 ambientColor, diffuseColor, specularColor; Float shininess; }; ViewerExample::ViewerExample(const Arguments& arguments): Platform::Application(arguments, Configuration().setTitle("Magnum Viewer")) { if(arguments.argc != 2) { Debug() << "Usage:" << arguments.argv[0] << "file.dae"; std::exit(0); } /* Instance ColladaImporter plugin */ PluginManager::Manager<Trade::AbstractImporter> manager(MAGNUM_PLUGINS_IMPORTER_DIR); if(manager.load("ColladaImporter") != PluginManager::LoadState::Loaded) { Error() << "Could not load ColladaImporter plugin"; std::exit(1); } Trade::AbstractImporter* importer = manager.instance("ColladaImporter"); if(importer) resourceManager.set("importer", importer, ResourceDataState::Final, ResourcePolicy::Manual); else { Error() << "Could not instance ColladaImporter plugin"; std::exit(2); } /* Every scene needs a camera */ (cameraObject = new Object3D(&scene)) ->translate(Vector3::zAxis(5)); (camera = new SceneGraph::Camera3D(cameraObject)) ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) ->setPerspective(35.0_degf, 1.0f, 0.001f, 100); Renderer::setFeature(Renderer::Feature::DepthTest, true); Renderer::setFeature(Renderer::Feature::FaceCulling, true); Debug() << "Opening file" << arguments.argv[1]; /* Load file */ if(!importer->openFile(arguments.argv[1])) { std::exit(4); } if(!importer->sceneCount()) { std::exit(5); } /* Resource loaders */ auto meshLoader = new MeshLoader; auto materialLoader = new MaterialLoader; resourceManager.setLoader(meshLoader)->setLoader(materialLoader); /* Phong shader instance */ resourceManager.set("color", new Shaders::Phong); /* Fallback mesh for objects with no mesh */ resourceManager.setFallback(new Mesh); /* Fallback material for objects with no material */ auto material = new Trade::PhongMaterialData({}, 50.0f); material->ambientColor() = {0.0f, 0.0f, 0.0f}; material->diffuseColor() = {0.9f, 0.9f, 0.9f}; material->specularColor() = {1.0f, 1.0f, 1.0f}; resourceManager.setFallback(material); Debug() << "Adding default scene" << importer->sceneName(importer->defaultScene()); /* Default object, parent of all (for manipulation) */ o = new Object3D(&scene); /* Load the scene */ Trade::SceneData* scene = importer->scene(importer->defaultScene()); /* Add all children */ for(UnsignedInt objectId: scene->children3D()) addObject(importer, o, objectId); /* Importer, materials and loaders are not needed anymore */ resourceManager.setFallback<Trade::PhongMaterialData>(nullptr) ->setLoader<Mesh>(nullptr) ->setLoader<Trade::PhongMaterialData>(nullptr) ->clear<Trade::PhongMaterialData>() ->clear<Trade::AbstractImporter>(); Debug() << "Imported" << meshLoader->loadedCount() << "meshes and" << materialLoader->loadedCount() << "materials," << meshLoader->notFoundCount() << "meshes and" << materialLoader->notFoundCount() << "materials weren't found."; } void ViewerExample::viewportEvent(const Vector2i& size) { defaultFramebuffer.setViewport({{}, size}); camera->setViewport(size); } void ViewerExample::drawEvent() { defaultFramebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth); camera->draw(drawables); swapBuffers(); } void ViewerExample::mousePressEvent(MouseEvent& event) { switch(event.button()) { case MouseEvent::Button::Left: previousPosition = positionOnSphere(event.position()); break; case MouseEvent::Button::WheelUp: case MouseEvent::Button::WheelDown: { /* Distance between origin and near camera clipping plane */ Float distance = cameraObject->transformation().translation().z()-0-camera->near(); /* Move 15% of the distance back or forward */ distance *= 1 - (event.button() == MouseEvent::Button::WheelUp ? 1/0.85f : 0.85f); cameraObject->translate(Vector3::zAxis(distance), SceneGraph::TransformationType::Global); redraw(); break; } default: ; } } void ViewerExample::mouseReleaseEvent(MouseEvent& event) { if(event.button() == MouseEvent::Button::Left) previousPosition = Vector3(); } void ViewerExample::mouseMoveEvent(MouseMoveEvent& event) { Vector3 currentPosition = positionOnSphere(event.position()); Vector3 axis = Vector3::cross(previousPosition, currentPosition); if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return; o->rotate(Vector3::angle(previousPosition, currentPosition), axis.normalized()); previousPosition = currentPosition; redraw(); } Vector3 ViewerExample::positionOnSphere(const Vector2i& _position) const { Vector2 position = Vector2(_position*2)/camera->viewport() - Vector2(1.0f); Float length = position.length(); Vector3 result(length > 1.0f ? Vector3(position, 0.0f) : Vector3(position, 1.0f - length)); result.y() *= -1.0f; return result.normalized(); } void ViewerExample::addObject(Trade::AbstractImporter* importer, Object3D* parent, std::size_t objectId) { Trade::ObjectData3D* object = importer->object3D(objectId); Debug() << "Importing object" << importer->object3DName(objectId); /* Only meshes for now */ if(object->instanceType() == Trade::ObjectData3D::InstanceType::Mesh) { const auto materialName = importer->materialName(static_cast<Trade::MeshObjectData3D*>(object)->material()); const ResourceKey materialKey(materialName); /* Decide what object to add based on material type */ Resource<Trade::PhongMaterialData> material = resourceManager.get<Trade::PhongMaterialData>(materialKey); /* Color-only material */ if(!material->flags()) (new ViewedObject(importer->mesh3DName(object->instance()), materialKey, parent, &drawables)) ->setTransformation(object->transformation()); /* No other material types are supported yet */ else Error() << "Texture combination of material" << materialName << "is not supported"; } /* Recursively add children */ for(std::size_t id: object->children()) addObject(importer, o, id); } MeshLoader::MeshLoader(): importer(ViewerResourceManager::instance()->get<Trade::AbstractImporter>("importer")) { /* Fill key->name map */ for(UnsignedInt i = 0; i != importer->mesh3DCount(); ++i) keyMap.emplace(importer->mesh3DName(i), i); } void MeshLoader::doLoad(const ResourceKey key) { const UnsignedInt id = keyMap.at(key); Debug() << "Importing mesh" << importer->mesh3DName(id) << "..."; Trade::MeshData3D* data = importer->mesh3D(id); if(!data || !data->isIndexed() || !data->positionArrayCount() || !data->normalArrayCount() || data->primitive() != Mesh::Primitive::Triangles) { delete data; setNotFound(key); return; } /* Fill mesh data */ auto mesh = new Mesh; auto buffer = new Buffer; auto indexBuffer = new Buffer; MeshTools::interleave(mesh, buffer, Buffer::Usage::StaticDraw, data->positions(0), data->normals(0)); MeshTools::compressIndices(mesh, indexBuffer, Buffer::Usage::StaticDraw, data->indices()); mesh->addInterleavedVertexBuffer(buffer, 0, Shaders::Phong::Position(), Shaders::Phong::Normal()) ->setPrimitive(data->primitive()); /* Save things */ ViewerResourceManager::instance()->set(importer->mesh3DName(id) + "-vertices", buffer); ViewerResourceManager::instance()->set(importer->mesh3DName(id) + "-indices", indexBuffer); set(key, mesh); delete data; } MaterialLoader::MaterialLoader(): importer(ViewerResourceManager::instance()->get<Trade::AbstractImporter>("importer")) { /* Fill key->name map */ for(UnsignedInt i = 0; i != importer->materialCount(); ++i) keyMap.emplace(importer->materialName(i), i); } void MaterialLoader::doLoad(const ResourceKey key) { const UnsignedInt id = keyMap.at(key); Debug() << "Importing material" << importer->materialName(id); auto material = importer->material(id); if(material && material->type() == Trade::AbstractMaterialData::Type::Phong) set(key, static_cast<Trade::PhongMaterialData*>(material), ResourceDataState::Final, ResourcePolicy::Manual); else setNotFound(key); } ViewedObject::ViewedObject(const ResourceKey meshKey, const ResourceKey materialKey, Object3D* parent, SceneGraph::DrawableGroup3D* group): Object3D(parent), SceneGraph::Drawable3D(this, group), mesh(ViewerResourceManager::instance()->get<Mesh>(meshKey)), shader(ViewerResourceManager::instance()->get<Shaders::Phong>("color")) { Resource<Trade::PhongMaterialData> material = ViewerResourceManager::instance()->get<Trade::PhongMaterialData>(materialKey); ambientColor = material->ambientColor(); diffuseColor = material->diffuseColor(); specularColor = material->specularColor(); shininess = material->shininess(); } void ViewedObject::draw(const Matrix4& transformationMatrix, SceneGraph::AbstractCamera3D* camera) { shader->setAmbientColor(ambientColor) ->setDiffuseColor(diffuseColor) ->setSpecularColor(specularColor) ->setShininess(shininess) ->setLightPosition({-3.0f, 10.0f, 10.0f}) ->setTransformationMatrix(transformationMatrix) ->setNormalMatrix(transformationMatrix.rotation()) ->setProjectionMatrix(camera->projectionMatrix()) ->use(); mesh->draw(); } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::ViewerExample) <|endoftext|>
<commit_before>namespace math { namespace detail { template<class Policy> inline float lerp_check_mu(float t) { QASSERT(t >= 0 && t <= 1); return t; } template<> inline float lerp_check_mu<safe>(float t) { return clamp(t, 0.f, 1.f); } } template<class Policy = standard> inline float lerp(float a, float b, float t) { t = detail::lerp_check_mu<Policy>(t); float x = b - a; return a + x*t; } template<class T, class Policy> inline T lerp(T const& a, T const& b, float t) { t = detail::lerp_check_mu<Policy>(t); return (T)(a*(1.f - t) + b*t); } template <typename T, class Policy = standard> angle<T> lerp(angle<T> const& a, angle<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); auto start = a.radians; auto end = b.radians; auto difference = abs(end - start); if (difference > angle<T>::pi.radians) { // We need to add on to one of the values. if (end > start) { // We'll add it on to start... start += angle<T>::_2pi.radians; } else { // Add it on to end. end += angle<T>::_2pi.radians; } } return angle<T>(start + ((end - start) * t)); } //NO NO NO. let it use the generic template implementation //nlerm and slerp use the normal lerp so leave it commented!!! // template <typename T, class Policy = standard> quat<T> lerp(quat<T> const& a, quat<T> const& b, float t) // { // return nlerp(a, b, t); // } template<class T, class Policy = standard> inline vec2<T> lerp(vec2<T> const& a, vec2<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); auto x(b - a); return vec2<T>(a.x + x.x*T(t), a.y + x.y*T(t)); } template<class T, class Policy = standard> inline vec3<T> lerp(vec3<T> const& a, vec3<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); auto x(b - a); return vec3<T>(a.x + x.x*T(t), a.y + x.y*T(t), a.z + x.z*T(t)); } template<class T, class Policy = standard> inline vec4<T> lerp(vec4<T> const& a, vec4<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); auto x(b - a); return vec4<T>(a.x + x.x*T(t), a.y + x.y*T(t), a.z + x.z*T(t), a.w + x.w*T(t)); } template<typename T, class Policy> quat<T> nlerp(quat<T> const& a, quat<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); quat<T> result(math::uninitialized); T angle = dot(a, b); if (angle >= 0) { result = lerp(a, b, t); } else if (angle <= -0.9999) { result = t < T(0.5) ? a : b; } else { result = lerp(a, -b, t); } return normalized(result); } template<typename T, class Policy> quat<T> slerp(quat<T> const& a, quat<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); T angle = dot(a, b); T scale; T invscale; if (angle > T(0.998)) { scale = T(1) - t; invscale = t; return quat<T>((a*scale) + (b*invscale)); } else { if (angle < T(0)) { if (angle <= T(-0.9999)) { return quat<T>(t < T(0.5) ? a : b); } else { quat<T> qa(-a); angle = T(-1) * max(angle, T(-1)); T const theta = acos(angle); T const invsintheta = T(1) / sin(theta); scale = sin(theta * (T(1) - t)) * invsintheta; invscale = sin(theta * t) * invsintheta; return quat<T>((qa * scale) + (b*invscale)); } } else { T const theta = acos(angle); T const invsintheta = T(1) / sin(theta); scale = sin(theta * (T(1) - t)) * invsintheta; invscale = sin(theta * t) * invsintheta; return quat<T>((a*scale) + (b*invscale)); } } } } <commit_msg>fixed nasty interpolation bug<commit_after>namespace math { namespace detail { template<class Policy> inline float lerp_check_mu(float t) { QASSERT(t >= 0 && t <= 1); return t; } template<> inline float lerp_check_mu<safe>(float t) { return clamp(t, 0.f, 1.f); } } template<class Policy = standard> inline float lerp(float a, float b, float t) { t = detail::lerp_check_mu<Policy>(t); float x = b - a; return a + x*t; } template<class T, class Policy> inline T lerp(T const& a, T const& b, float t) { t = detail::lerp_check_mu<Policy>(t); return (T)(a*(1.f - t) + b*t); } template <typename T, class Policy = standard> angle<T> lerp(angle<T> const& a, angle<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); auto start = a.radians; auto end = b.radians; auto difference = abs(end - start); if (difference > angle<T>::pi.radians) { // We need to add on to one of the values. if (end > start) { // We'll add it on to start... start += angle<T>::_2pi.radians; } else { // Add it on to end. end += angle<T>::_2pi.radians; } } return angle<T>(start + ((end - start) * t)); } //NO NO NO. let it use the generic template implementation //nlerm and slerp use the normal lerp so leave it commented!!! // template <typename T, class Policy = standard> quat<T> lerp(quat<T> const& a, quat<T> const& b, float t) // { // return nlerp(a, b, t); // } template<class T, class Policy = standard> inline vec2<T> lerp(vec2<T> const& a, vec2<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); auto x(b - a); return vec2<T>(a.x + x.x*T(t), a.y + x.y*T(t)); } template<class T, class Policy = standard> inline vec3<T> lerp(vec3<T> const& a, vec3<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); auto x(b - a); return vec3<T>(a.x + x.x*T(t), a.y + x.y*T(t), a.z + x.z*T(t)); } template<class T, class Policy = standard> inline vec4<T> lerp(vec4<T> const& a, vec4<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); auto x(b - a); return vec4<T>(a.x + x.x*T(t), a.y + x.y*T(t), a.z + x.z*T(t), a.w + x.w*T(t)); } template<typename T, class Policy> quat<T> nlerp(quat<T> const& a, quat<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); quat<T> result(math::uninitialized); T angle = dot(a, b); if (angle >= 0) { result = lerp(a, b, t); } else { result = lerp(a, -b, t); } return normalized(result); } template<typename T, class Policy> quat<T> slerp(quat<T> const& a, quat<T> const& b, float t) { t = detail::lerp_check_mu<Policy>(t); T angle = dot(a, b); T scale; T invscale; if (angle > T(0.9999)) { return lerp(a, b, t); } else { if (angle < T(0)) { if (angle <= T(-0.9999)) { return lerp(a, -b, t); } else { quat<T> qa(-a); angle = T(-1) * max(angle, T(-1)); T const theta = acos(angle); T const invsintheta = T(1) / sin(theta); scale = sin(theta * (T(1) - t)) * invsintheta; invscale = sin(theta * t) * invsintheta; return quat<T>((qa * scale) + (b*invscale)); } } else { T const theta = acos(angle); T const invsintheta = T(1) / sin(theta); scale = sin(theta * (T(1) - t)) * invsintheta; invscale = sin(theta * t) * invsintheta; return quat<T>((a*scale) + (b*invscale)); } } } } <|endoftext|>
<commit_before>// ////////////////////////////////////////////////////////////////////// #ifndef __STDAIR_BOM_EVENTTYPES_HPP #define __STDAIR_BOM_EVENTTYPES_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <map> // Boost Smart Pointers #include <boost/shared_ptr.hpp> // StdAir #include <stdair/stdair_basic_types.hpp> #include <stdair/stdair_date_time_types.hpp> #include <stdair/stdair_demand_types.hpp> #include <stdair/basic/ProgressStatus.hpp> #include <stdair/bom/key_types.hpp> namespace stdair { /// Forward declarations struct EventStruct; /** * Define an element of a event list. */ typedef std::pair<const LongDuration_T, EventStruct> EventListElement_T; /** * Define a list of events. */ typedef std::map<const LongDuration_T, EventStruct> EventList_T; /** * Define a map allowing tracking the progress status for each * content key (e.g., demand stream key, DCP rule key). */ typedef std::map<const EventContentKey_T, ProgressStatus> NbOfEventsByContentKeyMap_T; } #endif // __STDAIR_BOM_EVENTTYPES_HPP <commit_msg>[Dev] Added a missing header (stdair_event_types.hpp).<commit_after>// ////////////////////////////////////////////////////////////////////// #ifndef __STDAIR_BOM_EVENTTYPES_HPP #define __STDAIR_BOM_EVENTTYPES_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <map> // Boost Smart Pointers #include <boost/shared_ptr.hpp> // StdAir #include <stdair/stdair_basic_types.hpp> #include <stdair/stdair_date_time_types.hpp> #include <stdair/stdair_event_types.hpp> #include <stdair/basic/ProgressStatus.hpp> #include <stdair/bom/key_types.hpp> namespace stdair { /// Forward declarations struct EventStruct; /** * Define an element of a event list. */ typedef std::pair<const LongDuration_T, EventStruct> EventListElement_T; /** * Define a list of events. */ typedef std::map<const LongDuration_T, EventStruct> EventList_T; /** * Define a map allowing tracking the progress status for each * content key (e.g., demand stream key, DCP rule key). */ typedef std::map<const EventContentKey_T, ProgressStatus> NbOfEventsByContentKeyMap_T; } #endif // __STDAIR_BOM_EVENTTYPES_HPP <|endoftext|>
<commit_before>#include "../../../ui.h" #include "nbind/nbind.h" #include <uv.h> #include <Windows.h> bool running = false; uv_thread_t *thread; uv_async_t * asyncCall; bool runningSteps = false; static void eventsPending(uv_async_t* handle) { Nan::HandleScope scope; while (uiMainStep(0)); runningSteps = false; } LRESULT CALLBACK onEvents(int nCode, WPARAM wParam, LPARAM lParam) { if (!runningSteps) { runningSteps = true; printf("%d\n", nCode); uv_async_send(asyncCall); } return CallNextHookEx(NULL, nCode, wParam, lParam); } void pollEvents(void* pThreadId) { int threadId = *((int *) pThreadId); SetWindowsHookEx( WH_CALLWNDPROC, onEvents, NULL, threadId ); asyncCall = new uv_async_t(); uv_async_init(uv_default_loop(), asyncCall, eventsPending); MSG msg; while(running && GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } } struct EventLoop { static void start () { if (running) { return; } running = true; uiMainSteps(); thread = new uv_thread_t(); int threadId = GetCurrentThreadId(); uv_thread_create(thread, pollEvents, &threadId); } static void stop () { if (!running) { return; } running = false; uiQuit(); uv_thread_join(thread); delete thread; } }; NBIND_CLASS(EventLoop) { method(start); method(stop); } <commit_msg>remove hook on quit<commit_after>#include "../../../ui.h" #include "nbind/nbind.h" #include <uv.h> #include <Windows.h> bool running = false; uv_thread_t *thread; uv_async_t * asyncCall; bool runningSteps = false; HHOOK hhook; static void eventsPending(uv_async_t* handle) { Nan::HandleScope scope; while (uiMainStep(0)); runningSteps = false; } LRESULT CALLBACK onEvents(int nCode, WPARAM wParam, LPARAM lParam) { if (!runningSteps) { runningSteps = true; //printf("%d\n", nCode); uv_async_send(asyncCall); } return CallNextHookEx(NULL, nCode, wParam, lParam); } void pollEvents(void* pThreadId) { int threadId = *((int *) pThreadId); hhook = SetWindowsHookEx( WH_CALLWNDPROC, onEvents, NULL, threadId ); asyncCall = new uv_async_t(); uv_async_init(uv_default_loop(), asyncCall, eventsPending); MSG msg; while(running && GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } } struct EventLoop { static void start () { if (running) { return; } running = true; uiMainSteps(); thread = new uv_thread_t(); int threadId = GetCurrentThreadId(); uv_thread_create(thread, pollEvents, &threadId); } static void stop () { if (!running) { return; } running = false; UnhookWindowsHookEx(hhook); uiQuit(); uv_thread_join(thread); delete thread; } }; NBIND_CLASS(EventLoop) { method(start); method(stop); } <|endoftext|>
<commit_before>#ifndef utf8_hh_INCLUDED #define utf8_hh_INCLUDED #include "assert.hh" #include "unicode.hh" #include "units.hh" #include <cstddef> namespace Kakoune { namespace utf8 { template<typename Iterator> [[gnu::always_inline]] inline char read(Iterator& it) noexcept { char c = *it; ++it; return c; } // return true if it points to the first byte of a (either single or // multibyte) character [[gnu::always_inline]] inline bool is_character_start(char c) noexcept { return (c & 0xC0) != 0x80; } namespace InvalidPolicy { struct Assert { Codepoint operator()(Codepoint cp) const { kak_assert(false); return cp; } }; struct Pass { Codepoint operator()(Codepoint cp) const noexcept { return cp; } }; } // returns the codepoint of the character whose first byte // is pointed by it template<typename InvalidPolicy = utf8::InvalidPolicy::Pass, typename Iterator, typename Sentinel> Codepoint read_codepoint(Iterator& it, const Sentinel& end) noexcept(noexcept(InvalidPolicy{}(0))) { if (it == end) return InvalidPolicy{}(-1); // According to rfc3629, UTF-8 allows only up to 4 bytes. // (21 bits codepoint) unsigned char byte = read(it); if ((byte & 0x80) == 0) // 0xxxxxxx return byte; if (it == end) return InvalidPolicy{}(byte); if ((byte & 0xE0) == 0xC0) // 110xxxxx return ((byte & 0x1F) << 6) | (read(it) & 0x3F); if ((byte & 0xF0) == 0xE0) // 1110xxxx { Codepoint cp = ((byte & 0x0F) << 12) | ((read(it) & 0x3F) << 6); if (it == end) return InvalidPolicy{}(cp); return cp | (read(it) & 0x3F); } if ((byte & 0xF8) == 0xF0) // 11110xxx { Codepoint cp = ((byte & 0x0F) << 18) | ((read(it) & 0x3F) << 12); if (it == end) return InvalidPolicy{}(cp); cp |= (read(it) & 0x3F) << 6; if (it == end) return InvalidPolicy{}(cp); return cp | (read(it) & 0x3F); } return InvalidPolicy{}(byte); } template<typename InvalidPolicy = utf8::InvalidPolicy::Pass, typename Iterator, typename Sentinel> Codepoint codepoint(Iterator it, const Sentinel& end) noexcept(noexcept(read_codepoint<InvalidPolicy>(it, end))) { return read_codepoint<InvalidPolicy>(it, end); } template<typename InvalidPolicy = utf8::InvalidPolicy::Pass> ByteCount codepoint_size(char byte) noexcept(noexcept(InvalidPolicy{}(0))) { if ((byte & 0x80) == 0) // 0xxxxxxx return 1; else if ((byte & 0xE0) == 0xC0) // 110xxxxx return 2; else if ((byte & 0xF0) == 0xE0) // 1110xxxx return 3; else if ((byte & 0xF8) == 0xF0) // 11110xxx return 4; else { InvalidPolicy{}(byte); return 1; } } struct invalid_codepoint{}; inline ByteCount codepoint_size(Codepoint cp) { if (cp <= 0x7F) return 1; else if (cp <= 0x7FF) return 2; else if (cp <= 0xFFFF) return 3; else if (cp <= 0x10FFFF) return 4; else throw invalid_codepoint{}; } template<typename Iterator, typename Sentinel> void to_next(Iterator& it, const Sentinel& end) noexcept { if (it != end) ++it; while (it != end and not is_character_start(*it)) ++it; } // returns an iterator to next character first byte template<typename Iterator, typename Sentinel> Iterator next(Iterator it, const Sentinel& end) noexcept { to_next(it, end); return it; } // returns it's parameter if it points to a character first byte, // or else returns next character first byte template<typename Iterator, typename Sentinel> Iterator finish(Iterator it, const Sentinel& end) noexcept { while (it != end and (*(it) & 0xC0) == 0x80) ++it; return it; } template<typename Iterator, typename Sentinel> void to_previous(Iterator& it, const Sentinel& begin) noexcept { if (it != begin) --it; while (it != begin and not is_character_start(*it)) --it; } // returns an iterator to the previous character first byte template<typename Iterator, typename Sentinel> Iterator previous(Iterator it, const Sentinel& begin) noexcept { to_previous(it, begin); return it; } // returns an iterator pointing to the first byte of the // dth character after (or before if d < 0) the character // pointed by it template<typename Iterator, typename Sentinel> Iterator advance(Iterator it, const Sentinel& end, CharCount d) noexcept { if (it == end) return it; if (d < 0) { while (it != end and d++ != 0) to_previous(it, end); } else if (d > 0) { while (it != end and d-- != 0) to_next(it, end); } return it; } // returns an iterator pointing to the first byte of the // character at the dth column after (or before if d < 0) // the character pointed by it template<typename Iterator, typename Sentinel> Iterator advance(Iterator it, const Sentinel& end, ColumnCount d) noexcept { if (it == end) return it; if (d < 0) { while (it != end and d < 0) { auto cur = it; to_previous(it, end); d += codepoint_width(codepoint(it, cur)); } } else if (d > 0) { auto begin = it; while (it != end and d > 0) { d -= codepoint_width(read_codepoint(it, end)); if (it != end and d < 0) to_previous(it, begin); } } return it; } // returns the character count between begin and end template<typename Iterator, typename Sentinel> CharCount distance(Iterator begin, const Sentinel& end) noexcept { CharCount dist = 0; while (begin != end) { if (is_character_start(read(begin))) ++dist; } return dist; } // returns the column count between begin and end template<typename Iterator, typename Sentinel> ColumnCount column_distance(Iterator begin, const Sentinel& end) noexcept { ColumnCount dist = 0; while (begin != end) dist += codepoint_width(read_codepoint(begin, end)); return dist; } // returns an iterator to the first byte of the character it is into template<typename Iterator, typename Sentinel> Iterator character_start(Iterator it, const Sentinel& begin) noexcept { while (it != begin and not is_character_start(*it)) --it; return it; } template<typename OutputIterator> void dump(OutputIterator&& it, Codepoint cp) { if (cp <= 0x7F) *it++ = cp; else if (cp <= 0x7FF) { *it++ = 0xC0 | (cp >> 6); *it++ = 0x80 | (cp & 0x3F); } else if (cp <= 0xFFFF) { *it++ = 0xE0 | (cp >> 12); *it++ = 0x80 | ((cp >> 6) & 0x3F); *it++ = 0x80 | (cp & 0x3F); } else if (cp <= 0x10FFFF) { *it++ = 0xF0 | (cp >> 18); *it++ = 0x80 | ((cp >> 12) & 0x3F); *it++ = 0x80 | ((cp >> 6) & 0x3F); *it++ = 0x80 | (cp & 0x3F); } else throw invalid_codepoint{}; } } } #endif // utf8_hh_INCLUDED <commit_msg>Use an InvalidPolicy in utf8::dump and utf8::codepoint_size<commit_after>#ifndef utf8_hh_INCLUDED #define utf8_hh_INCLUDED #include "assert.hh" #include "unicode.hh" #include "units.hh" #include <cstddef> namespace Kakoune { namespace utf8 { template<typename Iterator> [[gnu::always_inline]] inline char read(Iterator& it) noexcept { char c = *it; ++it; return c; } // return true if it points to the first byte of a (either single or // multibyte) character [[gnu::always_inline]] inline bool is_character_start(char c) noexcept { return (c & 0xC0) != 0x80; } namespace InvalidPolicy { struct Assert { Codepoint operator()(Codepoint cp) const { kak_assert(false); return cp; } }; struct Pass { Codepoint operator()(Codepoint cp) const noexcept { return cp; } }; } // returns the codepoint of the character whose first byte // is pointed by it template<typename InvalidPolicy = utf8::InvalidPolicy::Pass, typename Iterator, typename Sentinel> Codepoint read_codepoint(Iterator& it, const Sentinel& end) noexcept(noexcept(InvalidPolicy{}(0))) { if (it == end) return InvalidPolicy{}(-1); // According to rfc3629, UTF-8 allows only up to 4 bytes. // (21 bits codepoint) unsigned char byte = read(it); if ((byte & 0x80) == 0) // 0xxxxxxx return byte; if (it == end) return InvalidPolicy{}(byte); if ((byte & 0xE0) == 0xC0) // 110xxxxx return ((byte & 0x1F) << 6) | (read(it) & 0x3F); if ((byte & 0xF0) == 0xE0) // 1110xxxx { Codepoint cp = ((byte & 0x0F) << 12) | ((read(it) & 0x3F) << 6); if (it == end) return InvalidPolicy{}(cp); return cp | (read(it) & 0x3F); } if ((byte & 0xF8) == 0xF0) // 11110xxx { Codepoint cp = ((byte & 0x0F) << 18) | ((read(it) & 0x3F) << 12); if (it == end) return InvalidPolicy{}(cp); cp |= (read(it) & 0x3F) << 6; if (it == end) return InvalidPolicy{}(cp); return cp | (read(it) & 0x3F); } return InvalidPolicy{}(byte); } template<typename InvalidPolicy = utf8::InvalidPolicy::Pass, typename Iterator, typename Sentinel> Codepoint codepoint(Iterator it, const Sentinel& end) noexcept(noexcept(read_codepoint<InvalidPolicy>(it, end))) { return read_codepoint<InvalidPolicy>(it, end); } template<typename InvalidPolicy = utf8::InvalidPolicy::Pass> ByteCount codepoint_size(char byte) noexcept(noexcept(InvalidPolicy{}(0))) { if ((byte & 0x80) == 0) // 0xxxxxxx return 1; else if ((byte & 0xE0) == 0xC0) // 110xxxxx return 2; else if ((byte & 0xF0) == 0xE0) // 1110xxxx return 3; else if ((byte & 0xF8) == 0xF0) // 11110xxx return 4; else { InvalidPolicy{}(byte); return 1; } } template<typename InvalidPolicy = utf8::InvalidPolicy::Pass> ByteCount codepoint_size(Codepoint cp) noexcept(noexcept(InvalidPolicy{}(0))) { if (cp <= 0x7F) return 1; else if (cp <= 0x7FF) return 2; else if (cp <= 0xFFFF) return 3; else if (cp <= 0x10FFFF) return 4; else { InvalidPolicy{}(cp); return 0; } } template<typename Iterator, typename Sentinel> void to_next(Iterator& it, const Sentinel& end) noexcept { if (it != end) ++it; while (it != end and not is_character_start(*it)) ++it; } // returns an iterator to next character first byte template<typename Iterator, typename Sentinel> Iterator next(Iterator it, const Sentinel& end) noexcept { to_next(it, end); return it; } // returns it's parameter if it points to a character first byte, // or else returns next character first byte template<typename Iterator, typename Sentinel> Iterator finish(Iterator it, const Sentinel& end) noexcept { while (it != end and (*(it) & 0xC0) == 0x80) ++it; return it; } template<typename Iterator, typename Sentinel> void to_previous(Iterator& it, const Sentinel& begin) noexcept { if (it != begin) --it; while (it != begin and not is_character_start(*it)) --it; } // returns an iterator to the previous character first byte template<typename Iterator, typename Sentinel> Iterator previous(Iterator it, const Sentinel& begin) noexcept { to_previous(it, begin); return it; } // returns an iterator pointing to the first byte of the // dth character after (or before if d < 0) the character // pointed by it template<typename Iterator, typename Sentinel> Iterator advance(Iterator it, const Sentinel& end, CharCount d) noexcept { if (it == end) return it; if (d < 0) { while (it != end and d++ != 0) to_previous(it, end); } else if (d > 0) { while (it != end and d-- != 0) to_next(it, end); } return it; } // returns an iterator pointing to the first byte of the // character at the dth column after (or before if d < 0) // the character pointed by it template<typename Iterator, typename Sentinel> Iterator advance(Iterator it, const Sentinel& end, ColumnCount d) noexcept { if (it == end) return it; if (d < 0) { while (it != end and d < 0) { auto cur = it; to_previous(it, end); d += codepoint_width(codepoint(it, cur)); } } else if (d > 0) { auto begin = it; while (it != end and d > 0) { d -= codepoint_width(read_codepoint(it, end)); if (it != end and d < 0) to_previous(it, begin); } } return it; } // returns the character count between begin and end template<typename Iterator, typename Sentinel> CharCount distance(Iterator begin, const Sentinel& end) noexcept { CharCount dist = 0; while (begin != end) { if (is_character_start(read(begin))) ++dist; } return dist; } // returns the column count between begin and end template<typename Iterator, typename Sentinel> ColumnCount column_distance(Iterator begin, const Sentinel& end) noexcept { ColumnCount dist = 0; while (begin != end) dist += codepoint_width(read_codepoint(begin, end)); return dist; } // returns an iterator to the first byte of the character it is into template<typename Iterator, typename Sentinel> Iterator character_start(Iterator it, const Sentinel& begin) noexcept { while (it != begin and not is_character_start(*it)) --it; return it; } template<typename OutputIterator, typename InvalidPolicy = utf8::InvalidPolicy::Pass> void dump(OutputIterator&& it, Codepoint cp) { if (cp <= 0x7F) *it++ = cp; else if (cp <= 0x7FF) { *it++ = 0xC0 | (cp >> 6); *it++ = 0x80 | (cp & 0x3F); } else if (cp <= 0xFFFF) { *it++ = 0xE0 | (cp >> 12); *it++ = 0x80 | ((cp >> 6) & 0x3F); *it++ = 0x80 | (cp & 0x3F); } else if (cp <= 0x10FFFF) { *it++ = 0xF0 | (cp >> 18); *it++ = 0x80 | ((cp >> 12) & 0x3F); *it++ = 0x80 | ((cp >> 6) & 0x3F); *it++ = 0x80 | (cp & 0x3F); } else InvalidPolicy{}(cp); } } } #endif // utf8_hh_INCLUDED <|endoftext|>
<commit_before>#include <array> #include <tuple.hpp> #include <tbb/concurrent_hash_map.h> #include <nmmintrin.h> namespace var_hash_map { template<typename K> struct var_crc_hash { var_crc_hash() = default; var_crc_hash(const var_crc_hash& h) = default; inline bool equal(const K& j, const K& k) const noexcept { return j == k; } // Safety check static_assert(sizeof(K) == K::size, "sizeof(K) != K::size"); /* Specialized hash functions for known key_buf sizes */ template<typename U = K> inline size_t hash(const U& k, typename std::enable_if<U::size == 8>::type* = 0) const noexcept { return _mm_crc32_u64(0, k.data[0]); } template<typename U = K> inline size_t hash(const U& k, typename std::enable_if<U::size == 16>::type* = 0) const noexcept { uint64_t hash = 0; hash = _mm_crc32_u64(hash, k.data[0]); return _mm_crc32_u64(hash, k.data[8]); } template<typename U = K> inline size_t hash(const U& k, typename std::enable_if<U::size == 32>::type* = 0) const noexcept { uint64_t hash = 0; hash = _mm_crc32_u64(hash, k.data[0]); hash = _mm_crc32_u64(hash, k.data[8]); hash = _mm_crc32_u64(hash, k.data[16]); return _mm_crc32_u64(hash, k.data[24]); } template<typename U = K> inline size_t hash(const U& k, typename std::enable_if<U::size == 64>::type* = 0) const noexcept { uint64_t hash = 0; hash = _mm_crc32_u64(hash, k.data[0]); hash = _mm_crc32_u64(hash, k.data[8]); hash = _mm_crc32_u64(hash, k.data[16]); hash = _mm_crc32_u64(hash, k.data[24]); hash = _mm_crc32_u64(hash, k.data[32]); hash = _mm_crc32_u64(hash, k.data[40]); hash = _mm_crc32_u64(hash, k.data[48]); return _mm_crc32_u64(hash, k.data[56]); } /* Generic version for key_bufs of any length * TODO: Maybe do something fancy for size mod 4 = 0 */ inline size_t hash(const K& k) const noexcept { uint64_t hash = 0; for (size_t i = 0; i < K::size; ++i) { hash = _mm_crc32_u8(hash, k.data[i]); } return hash; } }; template<size_t key_size> struct key_buf { static constexpr size_t size = key_size; uint8_t data[key_size]; } __attribute__((__packed__)); template<size_t key_size> inline bool operator==(const key_buf<key_size>& lhs, const key_buf<key_size>& rhs) noexcept { return std::memcmp(lhs.data, rhs.data, key_size) == 0; } template<size_t key_size> using K = key_buf<key_size>; template<size_t value_size> using V = std::array<std::uint8_t, value_size>; } extern "C" { using namespace var_hash_map; #define MAP_IMPL(key_size, value_size) \ template class tbb::concurrent_hash_map<K<key_size>, V<value_size>, var_crc_hash<K<key_size>>>; \ using hmapk##key_size##v##value_size = tbb::concurrent_hash_map<K<key_size>, V<value_size>, var_crc_hash<K<key_size>>>; \ hmapk##key_size##v##value_size* hmapk##key_size##v##value_size##_create() { \ return new hmapk##key_size##v##value_size; \ } \ void hmapk##key_size##v##value_size##_delete(hmapk##key_size##v##value_size* map) { \ delete map; \ } \ void hmapk##key_size##v##value_size##_clear(hmapk##key_size##v##value_size* map) { \ map->clear(); \ } \ hmapk##key_size##v##value_size::accessor* hmapk##key_size##v##value_size##_new_accessor() { \ return new hmapk##key_size##v##value_size::accessor; \ } \ void hmapk##key_size##v##value_size##_accessor_free(hmapk##key_size##v##value_size::accessor* a) { \ a->release(); \ delete a; \ } \ void hmapk##key_size##v##value_size##_accessor_release(hmapk##key_size##v##value_size::accessor* a) { \ a->release(); \ } \ bool hmapk##key_size##v##value_size##_access(hmapk##key_size##v##value_size* map, hmapk##key_size##v##value_size::accessor* a, const void* key) { \ return map->insert(*a, *static_cast<const K<key_size>*>(key)); \ } \ std::uint8_t* hmapk##key_size##v##value_size##_accessor_get_value(hmapk##key_size##v##value_size::accessor* a) { \ return (*a)->second.data(); \ } \ bool hmapk##key_size##v##value_size##_erase(hmapk##key_size##v##value_size* map, hmapk##key_size##v##value_size::accessor* a) { \ if (a->empty()) std::terminate();\ return map->erase(*a); \ } #define MAP_VALUES(value_size) \ MAP_IMPL(8, value_size) \ MAP_IMPL(16, value_size) \ MAP_IMPL(32, value_size) \ MAP_IMPL(64, value_size) MAP_VALUES(8) MAP_VALUES(16) MAP_VALUES(32) MAP_VALUES(64) MAP_VALUES(128) } <commit_msg>Fix grossly incorrect hash calculation<commit_after>#include <array> #include <tuple.hpp> #include <tbb/concurrent_hash_map.h> #include <nmmintrin.h> namespace var_hash_map { template<typename K> struct var_crc_hash { var_crc_hash() = default; var_crc_hash(const var_crc_hash& h) = default; inline bool equal(const K& j, const K& k) const noexcept { return j == k; } // Safety check static_assert(sizeof(K) == K::size, "sizeof(K) != K::size"); /* Specialized hash functions for known key_buf sizes */ template<typename U = K> inline size_t hash(const U& k, typename std::enable_if<U::size == 8>::type* = 0) const noexcept { return _mm_crc32_u64(0, *reinterpret_cast<const uint64_t*>(k.data + 0)); } template<typename U = K> inline size_t hash(const U& k, typename std::enable_if<U::size == 16>::type* = 0) const noexcept { uint32_t hash = 0; hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 0)); return _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 8)); } template<typename U = K> inline size_t hash(const U& k, typename std::enable_if<U::size == 32>::type* = 0) const noexcept { uint64_t hash = 0; hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 0)); hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 8)); hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 16)); return _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 24));; } template<typename U = K> inline size_t hash(const U& k, typename std::enable_if<U::size == 64>::type* = 0) const noexcept { uint64_t hash = 0; hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 0)); hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 8)); hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 16)); hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 24)); hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 32)); hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 40)); hash = _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 48)); return _mm_crc32_u64(hash, *reinterpret_cast<const uint64_t*>(k.data + 56));; } /* Generic version for key_bufs of any length * TODO: Maybe do something fancy for size mod 4 = 0 */ /* inline size_t hash(const K& k) const noexcept { uint64_t hash = 0; for (size_t i = 0; i < K::size; ++i) { hash = _mm_crc32_u8(hash, k.data[i]); } return hash; } */ }; template<size_t key_size> struct key_buf { static constexpr size_t size = key_size; uint8_t data[key_size]; } __attribute__((__packed__)); template<size_t key_size> inline bool operator==(const key_buf<key_size>& lhs, const key_buf<key_size>& rhs) noexcept { return std::memcmp(lhs.data, rhs.data, key_size) == 0; } template<size_t key_size> using K = key_buf<key_size>; template<size_t value_size> using V = std::array<std::uint8_t, value_size>; } extern "C" { using namespace var_hash_map; #define MAP_IMPL(key_size, value_size) \ template class tbb::concurrent_hash_map<K<key_size>, V<value_size>, var_crc_hash<K<key_size>>>; \ using hmapk##key_size##v##value_size = tbb::concurrent_hash_map<K<key_size>, V<value_size>, var_crc_hash<K<key_size>>>; \ hmapk##key_size##v##value_size* hmapk##key_size##v##value_size##_create() { \ return new hmapk##key_size##v##value_size; \ } \ void hmapk##key_size##v##value_size##_delete(hmapk##key_size##v##value_size* map) { \ delete map; \ } \ void hmapk##key_size##v##value_size##_clear(hmapk##key_size##v##value_size* map) { \ map->clear(); \ } \ hmapk##key_size##v##value_size::accessor* hmapk##key_size##v##value_size##_new_accessor() { \ return new hmapk##key_size##v##value_size::accessor; \ } \ void hmapk##key_size##v##value_size##_accessor_free(hmapk##key_size##v##value_size::accessor* a) { \ a->release(); \ delete a; \ } \ void hmapk##key_size##v##value_size##_accessor_release(hmapk##key_size##v##value_size::accessor* a) { \ a->release(); \ } \ bool hmapk##key_size##v##value_size##_access(hmapk##key_size##v##value_size* map, hmapk##key_size##v##value_size::accessor* a, const void* key) { \ return map->insert(*a, *static_cast<const K<key_size>*>(key)); \ } \ std::uint8_t* hmapk##key_size##v##value_size##_accessor_get_value(hmapk##key_size##v##value_size::accessor* a) { \ return (*a)->second.data(); \ } \ bool hmapk##key_size##v##value_size##_erase(hmapk##key_size##v##value_size* map, hmapk##key_size##v##value_size::accessor* a) { \ if (a->empty()) std::terminate();\ return map->erase(*a); \ } #define MAP_VALUES(value_size) \ MAP_IMPL(8, value_size) \ MAP_IMPL(16, value_size) \ MAP_IMPL(32, value_size) \ MAP_IMPL(64, value_size) MAP_VALUES(8) MAP_VALUES(16) MAP_VALUES(32) MAP_VALUES(64) MAP_VALUES(128) } <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkEndian.h" #include "SkFontStream.h" #include "SkStream.h" struct SkSFNTHeader { uint32_t fVersion; uint16_t fNumTables; uint16_t fSearchRange; uint16_t fEntrySelector; uint16_t fRangeShift; }; struct SkTTCFHeader { uint32_t fTag; uint32_t fVersion; uint32_t fNumOffsets; uint32_t fOffset0; // the first of N (fNumOffsets) }; union SkSharedTTHeader { SkSFNTHeader fSingle; SkTTCFHeader fCollection; }; struct SkSFNTDirEntry { uint32_t fTag; uint32_t fChecksum; uint32_t fOffset; uint32_t fLength; }; static bool read(SkStream* stream, void* buffer, size_t amount) { return stream->read(buffer, amount) == amount; } static bool skip(SkStream* stream, size_t amount) { return stream->skip(amount) == amount; } /** Return the number of tables, or if this is a TTC (collection), return the number of tables in the first element of the collection. In either case, if offsetToDir is not-null, set it to the offset to the beginning of the table headers (SkSFNTDirEntry), relative to the start of the stream. On an error, return 0 for number of tables, and ignore offsetToDir */ static int count_tables(SkStream* stream, int ttcIndex, size_t* offsetToDir) { SkASSERT(ttcIndex >= 0); SkAutoSMalloc<1024> storage(sizeof(SkSharedTTHeader)); SkSharedTTHeader* header = (SkSharedTTHeader*)storage.get(); if (!read(stream, header, sizeof(SkSharedTTHeader))) { return 0; } // by default, SkSFNTHeader is at the start of the stream size_t offset = 0; // if we're really a collection, the first 4-bytes will be 'ttcf' uint32_t tag = SkEndian_SwapBE32(header->fCollection.fTag); if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) { unsigned count = SkEndian_SwapBE32(header->fCollection.fNumOffsets); if ((unsigned)ttcIndex >= count) { return 0; } if (ttcIndex > 0) { // need to read more of the shared header stream->rewind(); size_t amount = sizeof(SkSharedTTHeader) + ttcIndex * sizeof(uint32_t); header = (SkSharedTTHeader*)storage.reset(amount); if (!read(stream, header, amount)) { return 0; } } // this is the offset to the local SkSFNTHeader offset = SkEndian_SwapBE32((&header->fCollection.fOffset0)[ttcIndex]); stream->rewind(); if (!skip(stream, offset)) { return 0; } if (!read(stream, header, sizeof(SkSFNTHeader))) { return 0; } } if (offsetToDir) { // add the size of the header, so we will point to the DirEntries *offsetToDir = offset + sizeof(SkSFNTHeader); } return SkEndian_SwapBE16(header->fSingle.fNumTables); } /////////////////////////////////////////////////////////////////////////////// struct SfntHeader { SfntHeader() : fCount(0), fDir(NULL) {} ~SfntHeader() { sk_free(fDir); } /** If it returns true, then fCount and fDir are properly initialized. Note: fDir will point to the raw array of SkSFNTDirEntry values, meaning they will still be in the file's native endianness (BE). fDir will be automatically freed when this object is destroyed */ bool init(SkStream* stream, int ttcIndex) { stream->rewind(); size_t offsetToDir; fCount = count_tables(stream, ttcIndex, &offsetToDir); if (0 == fCount) { return false; } stream->rewind(); if (!skip(stream, offsetToDir)) { return false; } size_t size = fCount * sizeof(SkSFNTDirEntry); fDir = reinterpret_cast<SkSFNTDirEntry*>(sk_malloc_throw(size)); return read(stream, fDir, size); } int fCount; SkSFNTDirEntry* fDir; }; /////////////////////////////////////////////////////////////////////////////// int SkFontStream::CountTTCEntries(SkStream* stream) { stream->rewind(); SkSharedTTHeader shared; if (!read(stream, &shared, sizeof(shared))) { return 0; } // if we're really a collection, the first 4-bytes will be 'ttcf' uint32_t tag = SkEndian_SwapBE32(shared.fCollection.fTag); if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) { return SkEndian_SwapBE32(shared.fCollection.fNumOffsets); } else { return 1; // normal 'sfnt' has 1 dir entry } } int SkFontStream::GetTableTags(SkStream* stream, int ttcIndex, SkFontTableTag tags[]) { SfntHeader header; if (!header.init(stream, ttcIndex)) { return 0; } if (tags) { for (int i = 0; i < header.fCount; i++) { tags[i] = SkEndian_SwapBE32(header.fDir[i].fTag); } } return header.fCount; } size_t SkFontStream::GetTableData(SkStream* stream, int ttcIndex, SkFontTableTag tag, size_t offset, size_t length, void* data) { SfntHeader header; if (!header.init(stream, ttcIndex)) { return 0; } for (int i = 0; i < header.fCount; i++) { if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) { size_t realOffset = SkEndian_SwapBE32(header.fDir[i].fOffset); size_t realLength = SkEndian_SwapBE32(header.fDir[i].fLength); // now sanity check the caller's offset/length if (offset >= realLength) { return 0; } // if the caller is trusting the length from the file, then a // hostile file might choose a value which would overflow offset + // length. if (offset + length < offset) { return 0; } if (length > realLength - offset) { length = realLength - offset; } if (data) { // skip the stream to the part of the table we want to copy from stream->rewind(); size_t bytesToSkip = realOffset + offset; if (skip(stream, bytesToSkip)) { return 0; } if (!read(stream, data, length)) { return 0; } } return length; } } return 0; } <commit_msg>fix missing ! typo when we switched to skip() helper function. caught by linux unittests.<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkEndian.h" #include "SkFontStream.h" #include "SkStream.h" struct SkSFNTHeader { uint32_t fVersion; uint16_t fNumTables; uint16_t fSearchRange; uint16_t fEntrySelector; uint16_t fRangeShift; }; struct SkTTCFHeader { uint32_t fTag; uint32_t fVersion; uint32_t fNumOffsets; uint32_t fOffset0; // the first of N (fNumOffsets) }; union SkSharedTTHeader { SkSFNTHeader fSingle; SkTTCFHeader fCollection; }; struct SkSFNTDirEntry { uint32_t fTag; uint32_t fChecksum; uint32_t fOffset; uint32_t fLength; }; static bool read(SkStream* stream, void* buffer, size_t amount) { return stream->read(buffer, amount) == amount; } static bool skip(SkStream* stream, size_t amount) { return stream->skip(amount) == amount; } /** Return the number of tables, or if this is a TTC (collection), return the number of tables in the first element of the collection. In either case, if offsetToDir is not-null, set it to the offset to the beginning of the table headers (SkSFNTDirEntry), relative to the start of the stream. On an error, return 0 for number of tables, and ignore offsetToDir */ static int count_tables(SkStream* stream, int ttcIndex, size_t* offsetToDir) { SkASSERT(ttcIndex >= 0); SkAutoSMalloc<1024> storage(sizeof(SkSharedTTHeader)); SkSharedTTHeader* header = (SkSharedTTHeader*)storage.get(); if (!read(stream, header, sizeof(SkSharedTTHeader))) { return 0; } // by default, SkSFNTHeader is at the start of the stream size_t offset = 0; // if we're really a collection, the first 4-bytes will be 'ttcf' uint32_t tag = SkEndian_SwapBE32(header->fCollection.fTag); if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) { unsigned count = SkEndian_SwapBE32(header->fCollection.fNumOffsets); if ((unsigned)ttcIndex >= count) { return 0; } if (ttcIndex > 0) { // need to read more of the shared header stream->rewind(); size_t amount = sizeof(SkSharedTTHeader) + ttcIndex * sizeof(uint32_t); header = (SkSharedTTHeader*)storage.reset(amount); if (!read(stream, header, amount)) { return 0; } } // this is the offset to the local SkSFNTHeader offset = SkEndian_SwapBE32((&header->fCollection.fOffset0)[ttcIndex]); stream->rewind(); if (!skip(stream, offset)) { return 0; } if (!read(stream, header, sizeof(SkSFNTHeader))) { return 0; } } if (offsetToDir) { // add the size of the header, so we will point to the DirEntries *offsetToDir = offset + sizeof(SkSFNTHeader); } return SkEndian_SwapBE16(header->fSingle.fNumTables); } /////////////////////////////////////////////////////////////////////////////// struct SfntHeader { SfntHeader() : fCount(0), fDir(NULL) {} ~SfntHeader() { sk_free(fDir); } /** If it returns true, then fCount and fDir are properly initialized. Note: fDir will point to the raw array of SkSFNTDirEntry values, meaning they will still be in the file's native endianness (BE). fDir will be automatically freed when this object is destroyed */ bool init(SkStream* stream, int ttcIndex) { stream->rewind(); size_t offsetToDir; fCount = count_tables(stream, ttcIndex, &offsetToDir); if (0 == fCount) { return false; } stream->rewind(); if (!skip(stream, offsetToDir)) { return false; } size_t size = fCount * sizeof(SkSFNTDirEntry); fDir = reinterpret_cast<SkSFNTDirEntry*>(sk_malloc_throw(size)); return read(stream, fDir, size); } int fCount; SkSFNTDirEntry* fDir; }; /////////////////////////////////////////////////////////////////////////////// int SkFontStream::CountTTCEntries(SkStream* stream) { stream->rewind(); SkSharedTTHeader shared; if (!read(stream, &shared, sizeof(shared))) { return 0; } // if we're really a collection, the first 4-bytes will be 'ttcf' uint32_t tag = SkEndian_SwapBE32(shared.fCollection.fTag); if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) { return SkEndian_SwapBE32(shared.fCollection.fNumOffsets); } else { return 1; // normal 'sfnt' has 1 dir entry } } int SkFontStream::GetTableTags(SkStream* stream, int ttcIndex, SkFontTableTag tags[]) { SfntHeader header; if (!header.init(stream, ttcIndex)) { return 0; } if (tags) { for (int i = 0; i < header.fCount; i++) { tags[i] = SkEndian_SwapBE32(header.fDir[i].fTag); } } return header.fCount; } size_t SkFontStream::GetTableData(SkStream* stream, int ttcIndex, SkFontTableTag tag, size_t offset, size_t length, void* data) { SfntHeader header; if (!header.init(stream, ttcIndex)) { return 0; } for (int i = 0; i < header.fCount; i++) { if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) { size_t realOffset = SkEndian_SwapBE32(header.fDir[i].fOffset); size_t realLength = SkEndian_SwapBE32(header.fDir[i].fLength); // now sanity check the caller's offset/length if (offset >= realLength) { return 0; } // if the caller is trusting the length from the file, then a // hostile file might choose a value which would overflow offset + // length. if (offset + length < offset) { return 0; } if (length > realLength - offset) { length = realLength - offset; } if (data) { // skip the stream to the part of the table we want to copy from stream->rewind(); size_t bytesToSkip = realOffset + offset; if (!skip(stream, bytesToSkip)) { return 0; } if (!read(stream, data, length)) { return 0; } } return length; } } return 0; } <|endoftext|>
<commit_before>#include <array> #include <string> #include <utility> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> #include <ics3/ics> class JointControlInterface { public: virtual void fetch() = 0; virtual void move() = 0; }; struct JointData { std::string name_; double cmd_; double pos_; double vel_; double eff_; }; template<class JntCmdInterface> struct JointControlBuildData { std::string joint_name_; hardware_interface::JointStateInterface& jnt_stat_; JntCmdInterface& jnt_cmd_; }; class ICSControl : public JointControlInterface { public: using JntCmdType = hardware_interface::PositionJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; ICSControl( BuildDataType&, const std::string&, const ics::ID&); void fetch() override; void move() override; private: JointData data_; }; template<class JntCmdInterface> void registerJoint( JointData&, hardware_interface::JointStateInterface&, JntCmdInterface&); template<class JntCmdInterface> void registerJoint( JointData&, JointControlBuildData<JntCmdInterface>&); int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); // // Arcsys2HW robot {}; // controller_manager::ControllerManager cm {&robot}; // // ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { // robot.read(); // cm.update(robot.getTime(), robot.getPeriod()); // robot.write(); // rate.sleep(); } spinner.stop(); return 0; } template<class JntCmdInterface> inline void registerJoint( JointData& joint, hardware_interface::JointStateInterface& jnt_stat, JntCmdInterface& jnt_cmd) { jnt_stat.registerHandle(hardware_interface::JointStateHandle {joint.name_, &joint.pos_, &joint.vel_, &joint.eff_}); jnt_cmd.registerHandle(hardware_interface::JointHandle {jnt_stat.getHandle(joint.name_), &joint.cmd_}); } template<class JntCmdInterface> inline void registerJoint( JointData& joint, JointControlBuildData<JntCmdInterface>& build_data) { registerJoint(joint, build_data.jnt_stat_, build_data.jnt_cmd_); } ICSControl::ICSControl( BuildDataType& build_data, const std::string& device_path, const ics::ID& id) : data_ {build_data.joint_name_} { registerJoint(data_, build_data); } void ICSControl::fetch() { } void ICSControl::move() { } <commit_msg>Add dammy joint<commit_after>#include <array> #include <string> #include <utility> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> #include <ics3/ics> class JointControlInterface { public: virtual void fetch() = 0; virtual void move() = 0; }; struct JointData { std::string name_; double cmd_; double pos_; double vel_; double eff_; }; template<class JntCmdInterface> struct JointControlBuildData { std::string joint_name_; hardware_interface::JointStateInterface& jnt_stat_; JntCmdInterface& jnt_cmd_; }; class ICSControl : public JointControlInterface { public: using JntCmdType = hardware_interface::PositionJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; ICSControl( BuildDataType&, const std::string&, const ics::ID&); void fetch() override; void move() override; private: JointData data_; }; class DammyControl : public JointControlInterface { public: using JntCmdType = hardware_interface::PositionJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; DammyControl(BuildDataType&); void fetch() override; void move() override; private: JointData data_; }; template<class JntCmdInterface> void registerJoint( JointData&, hardware_interface::JointStateInterface&, JntCmdInterface&); template<class JntCmdInterface> void registerJoint( JointData&, JointControlBuildData<JntCmdInterface>&); int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); // // Arcsys2HW robot {}; // controller_manager::ControllerManager cm {&robot}; // // ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { // robot.read(); // cm.update(robot.getTime(), robot.getPeriod()); // robot.write(); // rate.sleep(); } spinner.stop(); return 0; } template<class JntCmdInterface> inline void registerJoint( JointData& joint, hardware_interface::JointStateInterface& jnt_stat, JntCmdInterface& jnt_cmd) { jnt_stat.registerHandle(hardware_interface::JointStateHandle {joint.name_, &joint.pos_, &joint.vel_, &joint.eff_}); jnt_cmd.registerHandle(hardware_interface::JointHandle {jnt_stat.getHandle(joint.name_), &joint.cmd_}); } template<class JntCmdInterface> inline void registerJoint( JointData& joint, JointControlBuildData<JntCmdInterface>& build_data) { registerJoint(joint, build_data.jnt_stat_, build_data.jnt_cmd_); } ICSControl::ICSControl( BuildDataType& build_data, const std::string& device_path, const ics::ID& id) : data_ {build_data.joint_name_} { registerJoint(data_, build_data); } void ICSControl::fetch() { } void ICSControl::move() { } DammyControl::DammyControl(BuildDataType& build_data) : data_ {build_data.joint_name_} { registerJoint(data_, build_data); } void DammyControl::fetch() { data_.pos_ = data_.cmd_; } void DammyControl::move() { } <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "utils.h" #ifdef HAVE_PTHREAD_NAMING #include <pthread.h> #ifndef DEBUG #ifdef HAVE_PTHREAD_SET_NAME_NP #include <pthread_np.h> #endif #endif #elif defined(HAVE_SETPROCTITLE) #include <cstdlib> #elif defined(__linux__) #include <sys/prctl.h> #elif defined(_WIN32) || defined(_WIN64) #include <windows.h> #endif #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #else #include <cstdlib> #endif #if defined(_WIN32) || defined(_WIN64) static DWORD const current_thread = -1; static void SetThreadName(DWORD dwThreadID, LPCSTR threadName); #endif /** * \file utils.cxx * * \brief Implementation of pipeline utilities. */ namespace vistk { bool name_thread(thread_name_t const& name) { #ifdef HAVE_PTHREAD_NAMING #ifdef HAVE_PTHREAD_SETNAME_NP #ifdef PTHREAD_SETNAME_NP_TAKES_ID pthread_t const tid = pthread_self(); int const ret = pthread_setname_np(tid, name.c_str()); #else int const ret = pthread_setname_np(name.c_str()); #endif #elif defined(HAVE_PTHREAD_SET_NAME_NP) // The documentation states that it only makes sense in debugging; respect it. #ifndef NDEBUG pthread_t const tid = pthread_self(); int const ret = pthread_set_name_np(tid, name.c_str()); #else // Fail if not debugging. bool const ret = true; #endif #endif return !ret; #elif defined(HAVE_SETPROCTITLE) setproctitle("%s", name.c_str()); #elif defined(__linux__) int const ret = prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name.c_str()), 0, 0, 0); return (ret < 0); #elif defined(_WIN32) || defined(_WIN64) #ifndef NDEBUG SetThreadName(current_thread, name.c_str()); #else return false; #endif #else (void)name; return false; #endif return true; } envvar_value_t get_envvar(envvar_name_t const& name) { envvar_value_t value = NULL; #if defined(_WIN32) || defined(_WIN64) DWORD sz = GetEnvironmentVariable(name, NULL, 0); if (sz) { value = new char[sz]; sz = GetEnvironmentVariable(name, value, sz); } if (!sz) { /// \todo Log error that the environment reading failed. } #else value = getenv(name); #endif return value; } void free_envvar(envvar_value_t value) { #if defined(_WIN32) || defined(_WIN64) delete [] value; #else (void)value; #endif } } #if defined(_WIN32) || defined(_WIN64) // Code obtained from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx static DWORD const MS_VC_EXCEPTION = 0x406D1388; #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1 = caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) void SetThreadName(DWORD dwThreadID, LPCSTR threadName) { THREADNAME_INFO info; info.dwType = 0x1000; info.szName = threadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except(EXCEPTION_EXECUTE_HANDLER) { } } #endif <commit_msg>Only define Windows thread naming with debugging<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "utils.h" #ifdef HAVE_PTHREAD_NAMING #include <pthread.h> #ifndef DEBUG #ifdef HAVE_PTHREAD_SET_NAME_NP #include <pthread_np.h> #endif #endif #elif defined(HAVE_SETPROCTITLE) #include <cstdlib> #elif defined(__linux__) #include <sys/prctl.h> #elif defined(_WIN32) || defined(_WIN64) #include <windows.h> #endif #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #else #include <cstdlib> #endif #if defined(_WIN32) || defined(_WIN64) // The mechanism only make sense in debugging mode. #ifndef NDEBUG static DWORD const current_thread = -1; static void SetThreadName(DWORD dwThreadID, LPCSTR threadName); #endif #endif /** * \file utils.cxx * * \brief Implementation of pipeline utilities. */ namespace vistk { bool name_thread(thread_name_t const& name) { #ifdef HAVE_PTHREAD_NAMING #ifdef HAVE_PTHREAD_SETNAME_NP #ifdef PTHREAD_SETNAME_NP_TAKES_ID pthread_t const tid = pthread_self(); int const ret = pthread_setname_np(tid, name.c_str()); #else int const ret = pthread_setname_np(name.c_str()); #endif #elif defined(HAVE_PTHREAD_SET_NAME_NP) // The documentation states that it only makes sense in debugging; respect it. #ifndef NDEBUG pthread_t const tid = pthread_self(); int const ret = pthread_set_name_np(tid, name.c_str()); #else // Fail if not debugging. bool const ret = true; #endif #endif return !ret; #elif defined(HAVE_SETPROCTITLE) setproctitle("%s", name.c_str()); #elif defined(__linux__) int const ret = prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name.c_str()), 0, 0, 0); return (ret < 0); #elif defined(_WIN32) || defined(_WIN64) #ifndef NDEBUG SetThreadName(current_thread, name.c_str()); #else return false; #endif #else (void)name; return false; #endif return true; } envvar_value_t get_envvar(envvar_name_t const& name) { envvar_value_t value = NULL; #if defined(_WIN32) || defined(_WIN64) DWORD sz = GetEnvironmentVariable(name, NULL, 0); if (sz) { value = new char[sz]; sz = GetEnvironmentVariable(name, value, sz); } if (!sz) { /// \todo Log error that the environment reading failed. } #else value = getenv(name); #endif return value; } void free_envvar(envvar_value_t value) { #if defined(_WIN32) || defined(_WIN64) delete [] value; #else (void)value; #endif } } #if defined(_WIN32) || defined(_WIN64) #ifndef NDEBUG // Code obtained from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx static DWORD const MS_VC_EXCEPTION = 0x406D1388; #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1 = caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) void SetThreadName(DWORD dwThreadID, LPCSTR threadName) { THREADNAME_INFO info; info.dwType = 0x1000; info.szName = threadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except(EXCEPTION_EXECUTE_HANDLER) { } } #endif #endif <|endoftext|>
<commit_before>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/exception.h> namespace stingray { void _append_extended_diagnostics(string_ostream& result, const Detail::IToolkitException& tkit_ex) { const std::string backtrace = tkit_ex.GetBacktrace(); result << "\n in function '" << tkit_ex.GetFunctionName() << "'" << "\n in file '" << tkit_ex.GetFilename() << "' at line " << tkit_ex.GetLine(); if (!backtrace.empty()) result << "\n" << backtrace; } } <commit_msg>exception: drop no more needed check - backtrace will print stub string now if empty<commit_after>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/exception.h> namespace stingray { void _append_extended_diagnostics(string_ostream& result, const Detail::IToolkitException& tkit_ex) { result << "\n in function '" << tkit_ex.GetFunctionName() << "'" << "\n in file '" << tkit_ex.GetFilename() << "' at line " << tkit_ex.GetLine() << "\n" << tkit_ex.GetBacktrace(); } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "error.h" #include "utils.h" void create_shortcut(crwstr distro_name, crwstr file_path, crwstr icon_path) { auto hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); if (FAILED(hr)) throw error_hresult(err_create_shortcut, {}, hr); IShellLink *psl; hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl); if (FAILED(hr)) throw error_hresult(err_create_shortcut, {}, hr); wchar_t ep[MAX_PATH]; if (!GetModuleFileName(0, ep, MAX_PATH)) { error_win32_last(err_create_shortcut, {}); } psl->SetPath(ep); psl->SetDescription((L"Launch the WSL distribution " + distro_name + L'.').c_str()); psl->SetArguments((L"run -w -n " + distro_name).c_str()); if (!icon_path.empty()) psl->SetIconLocation(get_full_path(icon_path).c_str(), 0); IPersistFile *ppf; hr = psl->QueryInterface(IID_IPersistFile, (void **)&ppf); if (FAILED(hr)) throw error_hresult(err_create_shortcut, {}, hr); hr = ppf->Save(get_full_path(file_path).c_str(), true); if (FAILED(hr)) throw error_hresult(err_create_shortcut, {}, hr); ppf->Release(); psl->Release(); } <commit_msg>Quote distro name to allow space in it<commit_after>#include "stdafx.h" #include "error.h" #include "utils.h" void create_shortcut(crwstr distro_name, crwstr file_path, crwstr icon_path) { auto hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); if (FAILED(hr)) throw error_hresult(err_create_shortcut, {}, hr); IShellLink *psl; hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl); if (FAILED(hr)) throw error_hresult(err_create_shortcut, {}, hr); wchar_t ep[MAX_PATH]; if (!GetModuleFileName(0, ep, MAX_PATH)) { error_win32_last(err_create_shortcut, {}); } psl->SetPath(ep); psl->SetDescription((L"Launch the WSL distribution " + distro_name + L'.').c_str()); psl->SetArguments((L"run -w -n \"" + distro_name + L"\"").c_str()); if (!icon_path.empty()) psl->SetIconLocation(get_full_path(icon_path).c_str(), 0); IPersistFile *ppf; hr = psl->QueryInterface(IID_IPersistFile, (void **)&ppf); if (FAILED(hr)) throw error_hresult(err_create_shortcut, {}, hr); hr = ppf->Save(get_full_path(file_path).c_str(), true); if (FAILED(hr)) throw error_hresult(err_create_shortcut, {}, hr); ppf->Release(); psl->Release(); } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * Description: * What is this file about? * * Revision history: * xxxx-xx-xx, author, first version * xxxx-xx-xx, author, fix bug about xxx */ # include <dsn/service_api_c.h> # include <dsn/tool-api/command.h> # include <dsn/tool-api/logging_provider.h> # include <dsn/tool_api.h> # include "service_engine.h" # include <dsn/cpp/auto_codes.h> DSN_API dsn_log_level_t dsn_log_start_level = dsn_log_level_t::LOG_LEVEL_INFORMATION; static void log_on_sys_exit(::dsn::sys_exit_type) { ::dsn::logging_provider* logger = ::dsn::service_engine::fast_instance().logging(); if (logger != nullptr) { logger->flush(); } } void dsn_log_init() { dsn_log_start_level = enum_from_string( dsn_config_get_value_string("core", "logging_start_level", enum_to_string(dsn_log_start_level), "logs with level below this will not be logged"), dsn_log_level_t::LOG_LEVEL_INVALID ); dassert(dsn_log_start_level != dsn_log_level_t::LOG_LEVEL_INVALID, "invalid [core] logging_start_level specified"); // register log flush on exit bool logging_flush_on_exit = dsn_config_get_value_bool("core", "logging_flush_on_exit", true, "flush log when exit system"); if (logging_flush_on_exit) { ::dsn::tools::sys_exit.put_back(log_on_sys_exit, "log.flush"); } // register command for logging ::dsn::register_command("flush-log", "flush-log - flush log to stderr or log file", "flush-log - flush log to stderr or log file", [](const std::vector<std::string>& args) { ::dsn::logging_provider* logger = ::dsn::service_engine::fast_instance().logging(); if (logger != nullptr) { logger->flush(); } return "Flush done."; } ); ::dsn::register_command("reset-log-start-level", "reset-log-start-level [level_name] - reset log start level", "reset-log-start-level [level_name] - reset log start level", [](const std::vector<std::string>& args) { dsn_log_level_t start_level; if (args.size() == 0) { start_level = enum_from_string( dsn_config_get_value_string("core", "logging_start_level", enum_to_string(dsn_log_start_level), "logs with level below this will not be logged"), dsn_log_level_t::LOG_LEVEL_INVALID ); } else { start_level = enum_from_string( args[0].c_str(), dsn_log_level_t::LOG_LEVEL_INVALID ); if (start_level == dsn_log_level_t::LOG_LEVEL_INVALID) { return "ERROR: invalid level '" + args[0] + "'"; } } dsn_log_set_start_level(start_level); return std::string("OK, current level is ") + enum_to_string(start_level); } ); } DSN_API dsn_log_level_t dsn_log_get_start_level() { return dsn_log_start_level; } DSN_API void dsn_log_set_start_level(dsn_log_level_t level) { dsn_log_start_level = level; } DSN_API void dsn_logv(const char *file, const char *function, const int line, dsn_log_level_t log_level, const char* title, const char* fmt, va_list args) { ::dsn::logging_provider* logger = ::dsn::service_engine::instance().logging(); if (logger != nullptr) { logger->dsn_logv(file, function, line, log_level, title, fmt, args); } else { printf("%s:%d:%s():", title, line, function); vprintf(fmt, args); printf("\n"); } } DSN_API void dsn_logf(const char *file, const char *function, const int line, dsn_log_level_t log_level, const char* title, const char* fmt, ...) { va_list ap; va_start(ap, fmt); dsn_logv(file, function, line, log_level, title, fmt, ap); va_end(ap); } DSN_API void dsn_log(const char *file, const char *function, const int line, dsn_log_level_t log_level, const char* title) { dsn_logf(file, function, line, log_level, title, ""); } <commit_msg>small fix reset-log-start-level implement<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * Description: * What is this file about? * * Revision history: * xxxx-xx-xx, author, first version * xxxx-xx-xx, author, fix bug about xxx */ # include <dsn/service_api_c.h> # include <dsn/tool-api/command.h> # include <dsn/tool-api/logging_provider.h> # include <dsn/tool_api.h> # include "service_engine.h" # include <dsn/cpp/auto_codes.h> DSN_API dsn_log_level_t dsn_log_start_level = dsn_log_level_t::LOG_LEVEL_INFORMATION; static void log_on_sys_exit(::dsn::sys_exit_type) { ::dsn::logging_provider* logger = ::dsn::service_engine::fast_instance().logging(); if (logger != nullptr) { logger->flush(); } } void dsn_log_init() { dsn_log_start_level = enum_from_string( dsn_config_get_value_string("core", "logging_start_level", enum_to_string(dsn_log_start_level), "logs with level below this will not be logged"), dsn_log_level_t::LOG_LEVEL_INVALID ); dassert(dsn_log_start_level != dsn_log_level_t::LOG_LEVEL_INVALID, "invalid [core] logging_start_level specified"); // register log flush on exit bool logging_flush_on_exit = dsn_config_get_value_bool("core", "logging_flush_on_exit", true, "flush log when exit system"); if (logging_flush_on_exit) { ::dsn::tools::sys_exit.put_back(log_on_sys_exit, "log.flush"); } // register command for logging ::dsn::register_command("flush-log", "flush-log - flush log to stderr or log file", "flush-log", [](const std::vector<std::string>& args) { ::dsn::logging_provider* logger = ::dsn::service_engine::fast_instance().logging(); if (logger != nullptr) { logger->flush(); } return "Flush done."; } ); ::dsn::register_command("reset-log-start-level", "reset-log-start-level - reset the log start level", "reset-log-start-level [INFORMATION | DEBUG | WARNING | ERROR | FATAL]", [](const std::vector<std::string>& args) { dsn_log_level_t start_level; if (args.size() == 0) { start_level = enum_from_string( dsn_config_get_value_string("core", "logging_start_level", enum_to_string(dsn_log_start_level), "logs with level below this will not be logged"), dsn_log_level_t::LOG_LEVEL_INVALID ); } else { std::string level_str = "LOG_LEVEL_" + args[0]; start_level = enum_from_string( level_str.c_str(), dsn_log_level_t::LOG_LEVEL_INVALID ); if (start_level == dsn_log_level_t::LOG_LEVEL_INVALID) { return "ERROR: invalid level '" + args[0] + "'"; } } dsn_log_set_start_level(start_level); return std::string("OK, current level is ") + (enum_to_string(start_level) + 10); } ); } DSN_API dsn_log_level_t dsn_log_get_start_level() { return dsn_log_start_level; } DSN_API void dsn_log_set_start_level(dsn_log_level_t level) { dsn_log_start_level = level; } DSN_API void dsn_logv(const char *file, const char *function, const int line, dsn_log_level_t log_level, const char* title, const char* fmt, va_list args) { ::dsn::logging_provider* logger = ::dsn::service_engine::instance().logging(); if (logger != nullptr) { logger->dsn_logv(file, function, line, log_level, title, fmt, args); } else { printf("%s:%d:%s():", title, line, function); vprintf(fmt, args); printf("\n"); } } DSN_API void dsn_logf(const char *file, const char *function, const int line, dsn_log_level_t log_level, const char* title, const char* fmt, ...) { va_list ap; va_start(ap, fmt); dsn_logv(file, function, line, log_level, title, fmt, ap); va_end(ap); } DSN_API void dsn_log(const char *file, const char *function, const int line, dsn_log_level_t log_level, const char* title) { dsn_logf(file, function, line, log_level, title, ""); } <|endoftext|>
<commit_before>/*********************************************************************** filename: RenderTarget.inl created: Sun, 6th April 2014 author: Lukas E Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/Direct3D11/RenderTarget.h" #include "CEGUI/RendererModules/Direct3D11/GeometryBuffer.h" #include "CEGUI/RenderQueue.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <math.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> const double Direct3D11RenderTarget<T>::d_yfov_tan = 0.267949192431123; //----------------------------------------------------------------------------// template <typename T> Direct3D11RenderTarget<T>::Direct3D11RenderTarget(Direct3D11Renderer& owner) : d_owner(owner), d_device(*d_owner.getDirect3DDevice()), d_deviceContext(*d_owner.getDirect3DDeviceContext()), d_area(0, 0, 0, 0), d_viewDistance(0), d_matrixValid(false) { } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::draw(const GeometryBuffer& buffer) { buffer.draw(); } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::draw(const RenderQueue& queue) { queue.draw(); } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::setArea(const Rectf& area) { d_area = area; d_matrixValid = false; RenderTargetEventArgs args(this); T::fireEvent(RenderTarget::EventAreaChanged, args); } //----------------------------------------------------------------------------// template <typename T> const Rectf& Direct3D11RenderTarget<T>::getArea() const { return d_area; } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::activate() { if (!d_matrixValid) updateMatrix(); D3D11_VIEWPORT vp; setupViewport(vp); d_deviceContext.RSSetViewports(1, &vp); d_owner.setViewProjectionMatrix(d_projViewMatrix); } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::deactivate() { } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const Vector2f& p_in, Vector2f& p_out) const { if (!d_matrixValid) updateMatrix(); const Direct3D11GeometryBuffer& gb = static_cast<const Direct3D11GeometryBuffer&>(buff); const int vp[4] = { static_cast<int>(d_area.left()), static_cast<int>(d_area.top()), static_cast<int>(d_area.getWidth()), static_cast<int>(d_area.getHeight()) }; double in_x, in_y, in_z; glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); const glm::mat4& projMatrix = d_projViewMatrix; const glm::mat4& modelMatrix = gb.getMatrix(); // unproject the ends of the ray glm::vec3 unprojected1; glm::vec3 unprojected2; in_x = vp[2] * 0.5; in_y = vp[3] * 0.5; in_z = -d_viewDistance; unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = p_in.d_x; in_y = vp[3] - p_in.d_y; in_z = 0.0; unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // project points to orientate them with GeometryBuffer plane glm::vec3 projected1; glm::vec3 projected2; glm::vec3 projected3; in_x = 0.0; in_y = 0.0; projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 1.0; in_y = 0.0; projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 0.0; in_y = 1.0; projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // calculate vectors for generating the plane const glm::vec3 pv1 = projected2 - projected1; const glm::vec3 pv2 = projected3 - projected1; // given the vectors, calculate the plane normal const glm::vec3 planeNormal = glm::cross(pv1, pv2); // calculate plane const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal); const double pl_d = - glm::dot(projected1, planeNormalNormalized); // calculate vector of picking ray const glm::vec3 rv = unprojected1 - unprojected2; // calculate intersection of ray and plane const double pn_dot_r1 = glm::dot(unprojected1, planeNormal); const double pn_dot_rv = glm::dot(rv, planeNormal); const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0; const double is_x = unprojected1.x - rv.x * tmp1; const double is_y = unprojected1.y - rv.y * tmp1; p_out.d_x = static_cast<float>(is_x); p_out.d_y = static_cast<float>(is_y); p_out = p_in; // CrazyEddie wanted this } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::updateMatrix() const { const float w = d_area.getWidth(); const float h = d_area.getHeight(); const float aspect = w / h; const float midx = w * 0.5f; const float midy = h * 0.5f; d_viewDistance = midx / (aspect * d_yfov_tan); glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance)); glm::vec3 center = glm::vec3(midx, midy, 1); glm::vec3 up = glm::vec3(0, -1, 0); const float fovy = 30.f; const float zNear = static_cast<float>(d_viewDistance * 0.5f); const float zFar = static_cast<float>(d_viewDistance * 2.0f); const float f = 1.0f / std::tan(fovy * glm::pi<float>() * 0.5f / 180.0f); const float Q = zFar / (zNear - zFar); // We need to have a projection matrix with its depth in clip space ranging from 0 to 1 for nearclip to farclip. // The regular OpenGL projection matrix would work too, but we would lose 1 bit of depth precision, which this matrix should fix: float projectionMatrixFloat[16] = { f/aspect, 0.0f, 0.0f, 0.0f, 0.0f, f, 0.0f, 0.0f, 0.0f, 0.0f, Q, -1.0f, 0.0f, 0.0f, Q * zNear, 0.0f }; glm::mat4 projectionMatrix = glm::make_mat4(projectionMatrixFloat); // Projection matrix abuse! glm::mat4 viewMatrix = glm::lookAt(eye, center, up); d_projViewMatrix = projectionMatrix * viewMatrix; d_matrixValid = true; } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::setupViewport(D3D11_VIEWPORT& vp) const { vp.TopLeftX = static_cast<FLOAT>(d_area.left()); vp.TopLeftY = static_cast<FLOAT>(d_area.top()); vp.Width = static_cast<FLOAT>(d_area.getWidth()); vp.Height = static_cast<FLOAT>(d_area.getHeight()); vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>FIX: Missing include added - Thanks to lucebac for providing the fix<commit_after>/*********************************************************************** filename: RenderTarget.inl created: Sun, 6th April 2014 author: Lukas E Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/Direct3D11/RenderTarget.h" #include "CEGUI/RendererModules/Direct3D11/GeometryBuffer.h" #include "CEGUI/RenderQueue.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/constants.hpp> #include <math.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> const double Direct3D11RenderTarget<T>::d_yfov_tan = 0.267949192431123; //----------------------------------------------------------------------------// template <typename T> Direct3D11RenderTarget<T>::Direct3D11RenderTarget(Direct3D11Renderer& owner) : d_owner(owner), d_device(*d_owner.getDirect3DDevice()), d_deviceContext(*d_owner.getDirect3DDeviceContext()), d_area(0, 0, 0, 0), d_viewDistance(0), d_matrixValid(false) { } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::draw(const GeometryBuffer& buffer) { buffer.draw(); } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::draw(const RenderQueue& queue) { queue.draw(); } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::setArea(const Rectf& area) { d_area = area; d_matrixValid = false; RenderTargetEventArgs args(this); T::fireEvent(RenderTarget::EventAreaChanged, args); } //----------------------------------------------------------------------------// template <typename T> const Rectf& Direct3D11RenderTarget<T>::getArea() const { return d_area; } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::activate() { if (!d_matrixValid) updateMatrix(); D3D11_VIEWPORT vp; setupViewport(vp); d_deviceContext.RSSetViewports(1, &vp); d_owner.setViewProjectionMatrix(d_projViewMatrix); } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::deactivate() { } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const Vector2f& p_in, Vector2f& p_out) const { if (!d_matrixValid) updateMatrix(); const Direct3D11GeometryBuffer& gb = static_cast<const Direct3D11GeometryBuffer&>(buff); const int vp[4] = { static_cast<int>(d_area.left()), static_cast<int>(d_area.top()), static_cast<int>(d_area.getWidth()), static_cast<int>(d_area.getHeight()) }; double in_x, in_y, in_z; glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); const glm::mat4& projMatrix = d_projViewMatrix; const glm::mat4& modelMatrix = gb.getMatrix(); // unproject the ends of the ray glm::vec3 unprojected1; glm::vec3 unprojected2; in_x = vp[2] * 0.5; in_y = vp[3] * 0.5; in_z = -d_viewDistance; unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = p_in.d_x; in_y = vp[3] - p_in.d_y; in_z = 0.0; unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // project points to orientate them with GeometryBuffer plane glm::vec3 projected1; glm::vec3 projected2; glm::vec3 projected3; in_x = 0.0; in_y = 0.0; projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 1.0; in_y = 0.0; projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 0.0; in_y = 1.0; projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // calculate vectors for generating the plane const glm::vec3 pv1 = projected2 - projected1; const glm::vec3 pv2 = projected3 - projected1; // given the vectors, calculate the plane normal const glm::vec3 planeNormal = glm::cross(pv1, pv2); // calculate plane const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal); const double pl_d = - glm::dot(projected1, planeNormalNormalized); // calculate vector of picking ray const glm::vec3 rv = unprojected1 - unprojected2; // calculate intersection of ray and plane const double pn_dot_r1 = glm::dot(unprojected1, planeNormal); const double pn_dot_rv = glm::dot(rv, planeNormal); const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0; const double is_x = unprojected1.x - rv.x * tmp1; const double is_y = unprojected1.y - rv.y * tmp1; p_out.d_x = static_cast<float>(is_x); p_out.d_y = static_cast<float>(is_y); p_out = p_in; // CrazyEddie wanted this } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::updateMatrix() const { const float w = d_area.getWidth(); const float h = d_area.getHeight(); const float aspect = w / h; const float midx = w * 0.5f; const float midy = h * 0.5f; d_viewDistance = midx / (aspect * d_yfov_tan); glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance)); glm::vec3 center = glm::vec3(midx, midy, 1); glm::vec3 up = glm::vec3(0, -1, 0); const float fovy = 30.f; const float zNear = static_cast<float>(d_viewDistance * 0.5f); const float zFar = static_cast<float>(d_viewDistance * 2.0f); const float f = 1.0f / std::tan(fovy * glm::pi<float>() * 0.5f / 180.0f); const float Q = zFar / (zNear - zFar); // We need to have a projection matrix with its depth in clip space ranging from 0 to 1 for nearclip to farclip. // The regular OpenGL projection matrix would work too, but we would lose 1 bit of depth precision, which this matrix should fix: float projectionMatrixFloat[16] = { f/aspect, 0.0f, 0.0f, 0.0f, 0.0f, f, 0.0f, 0.0f, 0.0f, 0.0f, Q, -1.0f, 0.0f, 0.0f, Q * zNear, 0.0f }; glm::mat4 projectionMatrix = glm::make_mat4(projectionMatrixFloat); // Projection matrix abuse! glm::mat4 viewMatrix = glm::lookAt(eye, center, up); d_projViewMatrix = projectionMatrix * viewMatrix; d_matrixValid = true; } //----------------------------------------------------------------------------// template <typename T> void Direct3D11RenderTarget<T>::setupViewport(D3D11_VIEWPORT& vp) const { vp.TopLeftX = static_cast<FLOAT>(d_area.left()); vp.TopLeftY = static_cast<FLOAT>(d_area.top()); vp.Width = static_cast<FLOAT>(d_area.getWidth()); vp.Height = static_cast<FLOAT>(d_area.getHeight()); vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>/* * This file is part of the rc_dynamics_api package. * * Copyright (c) 2017 Roboception GmbH * All rights reserved * * Author: Christian Emmerich * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "remote_interface.h" #include "unexpected_receive_timeout.h" #include <json.hpp> #include <cpr/cpr.h> using namespace std; using json = nlohmann::json; namespace rc { namespace dynamics { string toString(cpr::Response resp) { stringstream s; s << "status code: " << resp.status_code << endl << "url: " << resp.url << endl << "text: " << resp.text << endl << "error: " << resp.error.message; return s.str(); } string toString(list<string> list) { stringstream s; s << "["; for (auto it = list.begin(); it != list.end();) { s << *it; if (++it != list.end()) { s << ", "; } } s << "]"; return s.str(); } void handleCPRResponse(cpr::Response r) { if (r.status_code != 200) { throw runtime_error(toString(r)); } } /** * Class for data stream receivers that are created by this * remote interface in order to keep track of created streams. * */ class TrackedDataReceiver : public DataReceiver { public: static shared_ptr<TrackedDataReceiver> create(const string &ip_address, unsigned int &port, const string &stream, shared_ptr<RemoteInterface> creator) { return shared_ptr<TrackedDataReceiver>( new TrackedDataReceiver(ip_address, port, stream, creator)); } virtual ~TrackedDataReceiver() { try { _creator->deleteDestinationFromStream(_stream, _dest); } catch (exception &e) { cerr << "[TrackedDataReceiver] Could not remove my destination " << _dest << " for stream type " << _stream << " from rc_visard: " << e.what() << endl; } } protected: TrackedDataReceiver(const string &ip_address, unsigned int &port, const string &stream, shared_ptr<RemoteInterface> creator) : DataReceiver(ip_address, port), _dest(ip_address + ":" + to_string(port)), _stream(stream), _creator(creator) {} string _dest, _stream; shared_ptr<RemoteInterface> _creator; }; // map to store already created RemoteInterface objects map<string, RemoteInterface::Ptr> RemoteInterface::_remoteInterfaces = map<string,RemoteInterface::Ptr>(); RemoteInterface::Ptr RemoteInterface::create(const string &rcVisardInetAddrs, unsigned int requestsTimeout) { // check if interface is already opened auto found = RemoteInterface::_remoteInterfaces.find(rcVisardInetAddrs); if (found != RemoteInterface::_remoteInterfaces.end()) { return found->second; } // if not, create it auto newRemoteInterface = Ptr( new RemoteInterface(rcVisardInetAddrs, requestsTimeout)); RemoteInterface::_remoteInterfaces[rcVisardInetAddrs] = newRemoteInterface; return newRemoteInterface; } RemoteInterface::RemoteInterface(const string &rcVisardIP, unsigned int requestsTimeout) : _visardAddrs(rcVisardIP), _baseUrl("http://" + _visardAddrs + "/api/v1"), _timeoutCurl(requestsTimeout) { _reqStreams.clear(); _protobufMap.clear(); // check if given string is a valid IP address if (!isValidIPAddress(rcVisardIP)) { throw invalid_argument("Given IP address is not a valid address: " + rcVisardIP); } // initial connection to rc_visard and get streams, i.e. do get request on // respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/datastreams"}; auto get = cpr::Get(url, cpr::Timeout{_timeoutCurl}); handleCPRResponse(get); // parse text of response into json object auto j = json::parse(get.text); for (const auto& stream : j) { _availStreams.push_back(stream["name"]); _protobufMap[stream["name"]] = stream["protobuf"]; } } RemoteInterface::~RemoteInterface() { cleanUpRequestedStreams(); for (const auto& s : _reqStreams) { if (s.second.size() > 0) { cerr << "[RemoteInterface] Could not stop all previously requested" " streams of type " << s.first << " on rc_visard. Please check " "device manually" " (" << _baseUrl << "/datastreams/" << s.first << ")" " for not containing any of the following legacy streams and" " delete them otherwise, e.g. using the swagger UI (" << "http://" + _visardAddrs + "/api/swagger/)" << ": " << toString(s.second) << endl; } } } RemoteInterface::State RemoteInterface::callDynamicsService(std::string serviceName) { cpr::Url url = cpr::Url{ _baseUrl + "/nodes/rc_dynamics/services/" + serviceName}; auto response = cpr::Put(url, cpr::Timeout{_timeoutCurl}); handleCPRResponse(response); auto j = json::parse(response.text); int entered_state = j["enteredState"].get<int>(); if(entered_state < static_cast<int>(State::IDLE) or entered_state > static_cast<int>(State::RUNNING_WITH_SLAM)) { //mismatch between rc_dynamics states and states used in this class? throw invalid_state(entered_state); } return static_cast<State>(entered_state); } RemoteInterface::State RemoteInterface::restart() { return callDynamicsService("restart"); } RemoteInterface::State RemoteInterface::start() { return callDynamicsService("start"); } RemoteInterface::State RemoteInterface::startSlam() { return callDynamicsService("start_slam"); } RemoteInterface::State RemoteInterface::stop() { return callDynamicsService("stop"); } RemoteInterface::State RemoteInterface::stopSlam() { return callDynamicsService("stop_slam"); } RemoteInterface::State RemoteInterface::getState() { return callDynamicsService("getstate"); } /* Replaced by above method RemoteInterface::State RemoteInterface::getState() { // do get request on respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/nodes/rc_dynamics/services/getstate"}; auto get = cpr::Get(url, cpr::Timeout{_timeoutCurl}); handleCPRResponse(get); // parse text of response into json object auto j = json::parse(get.text); if (j["status"].get<string>() == "running") return State::RUNNING; else return State::STOPPED; } */ list<string> RemoteInterface::getAvailableStreams() { return _availStreams; } string RemoteInterface::getPbMsgTypeOfStream(const string &stream) { checkStreamTypeAvailable(stream); return _protobufMap[stream]; } list<string> RemoteInterface::getDestinationsOfStream(const string &stream) { checkStreamTypeAvailable(stream); list<string> destinations; // do get request on respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/datastreams/" + stream}; auto get = cpr::Get(url, cpr::Timeout{_timeoutCurl}); handleCPRResponse(get); // parse result as json auto j = json::parse(get.text); for (auto dest : j["destinations"]) { destinations.push_back(dest.get<string>()); } return destinations; } void RemoteInterface::addDestinationToStream(const string &stream, const string &destination) { checkStreamTypeAvailable(stream); // do put request on respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/datastreams/" + stream}; auto put = cpr::Put(url, cpr::Timeout{_timeoutCurl}, cpr::Parameters{{"destination", destination}}); handleCPRResponse(put); // keep track of added destinations _reqStreams[stream].push_back(destination); } void RemoteInterface::deleteDestinationFromStream(const string &stream, const string &destination) { checkStreamTypeAvailable(stream); // do delete request on respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/datastreams/" + stream}; auto del = cpr::Delete(url, cpr::Timeout{_timeoutCurl}, cpr::Parameters{{"destination", destination}}); handleCPRResponse(del); // delete destination also from list of requested streams auto& destinations = _reqStreams[stream]; auto found = find(destinations.begin(), destinations.end(), destination); if (found != destinations.end()) destinations.erase(found); } DataReceiver::Ptr RemoteInterface::createReceiverForStream(const string &stream, const string &destInterface, unsigned int destPort) { checkStreamTypeAvailable(stream); // figure out local inet address for streaming string destAddress; if (!getThisHostsIP(destAddress, _visardAddrs, destInterface)) { stringstream msg; msg << "Could not infer a valid IP address " "for this host as the destination of the stream! " "Given network interface specification was '" << destInterface << "'."; throw invalid_argument(msg.str()); } // create data receiver with port as specified DataReceiver::Ptr receiver = TrackedDataReceiver::create(destAddress, destPort, stream, shared_from_this()); // do REST-API call requesting a UDP stream from rc_visard device string destination = destAddress + ":" + to_string(destPort); addDestinationToStream(stream, destination); // waiting for first message; we set a long timeout for receiving data unsigned int initialTimeOut = 5000; receiver->setTimeout(initialTimeOut); if (!receiver->receive(_protobufMap[stream])) { throw UnexpectedReceiveTimeout(initialTimeOut); // stringstream msg; // msg << "Did not receive any data within the last " // << initialTimeOut << " ms. " // << "Either rc_visard does not seem to send the data properly " // "(is rc_dynamics module running?) or you seem to have serious " // "network/connection problems!"; // throw runtime_error(msg.str()); } // stream established, prepare everything for normal pose receiving receiver->setTimeout(100); return receiver; } void RemoteInterface::cleanUpRequestedStreams() { // for each stream type check currently running streams on rc_visard device for (auto const &s : _reqStreams) { // get a list of currently active streams of this type on rc_visard device list<string> rcVisardsActiveStreams; try { rcVisardsActiveStreams = getDestinationsOfStream(s.first); } catch (exception &e) { cerr << "[RemoteInterface] Could not get list of active " << s.first << " streams for cleaning up previously requested streams: " << e.what() << endl; continue; } // try to stop all previously requested streams of this type for (auto activeStream : rcVisardsActiveStreams) { auto found = find(s.second.begin(), s.second.end(), activeStream); if (found != s.second.end()) { try { deleteDestinationFromStream(s.first, activeStream); } catch (exception &e) { cerr << "[RemoteInterface] Could not delete destination " << activeStream << " from " << s.first << " stream: " << e.what() << endl; } } } } } void RemoteInterface::checkStreamTypeAvailable(const string& stream) { auto found = find(_availStreams.begin(), _availStreams.end(), stream); if (found == _availStreams.end()) { stringstream msg; msg << "Stream of type '" << stream << "' is not available on rc_visard " << _visardAddrs; throw invalid_argument(msg.str()); } } } } <commit_msg>Fix json parsing<commit_after>/* * This file is part of the rc_dynamics_api package. * * Copyright (c) 2017 Roboception GmbH * All rights reserved * * Author: Christian Emmerich * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "remote_interface.h" #include "unexpected_receive_timeout.h" #include <json.hpp> #include <cpr/cpr.h> using namespace std; using json = nlohmann::json; namespace rc { namespace dynamics { string toString(cpr::Response resp) { stringstream s; s << "status code: " << resp.status_code << endl << "url: " << resp.url << endl << "text: " << resp.text << endl << "error: " << resp.error.message; return s.str(); } string toString(list<string> list) { stringstream s; s << "["; for (auto it = list.begin(); it != list.end();) { s << *it; if (++it != list.end()) { s << ", "; } } s << "]"; return s.str(); } void handleCPRResponse(cpr::Response r) { if (r.status_code != 200) { throw runtime_error(toString(r)); } } /** * Class for data stream receivers that are created by this * remote interface in order to keep track of created streams. * */ class TrackedDataReceiver : public DataReceiver { public: static shared_ptr<TrackedDataReceiver> create(const string &ip_address, unsigned int &port, const string &stream, shared_ptr<RemoteInterface> creator) { return shared_ptr<TrackedDataReceiver>( new TrackedDataReceiver(ip_address, port, stream, creator)); } virtual ~TrackedDataReceiver() { try { _creator->deleteDestinationFromStream(_stream, _dest); } catch (exception &e) { cerr << "[TrackedDataReceiver] Could not remove my destination " << _dest << " for stream type " << _stream << " from rc_visard: " << e.what() << endl; } } protected: TrackedDataReceiver(const string &ip_address, unsigned int &port, const string &stream, shared_ptr<RemoteInterface> creator) : DataReceiver(ip_address, port), _dest(ip_address + ":" + to_string(port)), _stream(stream), _creator(creator) {} string _dest, _stream; shared_ptr<RemoteInterface> _creator; }; // map to store already created RemoteInterface objects map<string, RemoteInterface::Ptr> RemoteInterface::_remoteInterfaces = map<string,RemoteInterface::Ptr>(); RemoteInterface::Ptr RemoteInterface::create(const string &rcVisardInetAddrs, unsigned int requestsTimeout) { // check if interface is already opened auto found = RemoteInterface::_remoteInterfaces.find(rcVisardInetAddrs); if (found != RemoteInterface::_remoteInterfaces.end()) { return found->second; } // if not, create it auto newRemoteInterface = Ptr( new RemoteInterface(rcVisardInetAddrs, requestsTimeout)); RemoteInterface::_remoteInterfaces[rcVisardInetAddrs] = newRemoteInterface; return newRemoteInterface; } RemoteInterface::RemoteInterface(const string &rcVisardIP, unsigned int requestsTimeout) : _visardAddrs(rcVisardIP), _baseUrl("http://" + _visardAddrs + "/api/v1"), _timeoutCurl(requestsTimeout) { _reqStreams.clear(); _protobufMap.clear(); // check if given string is a valid IP address if (!isValidIPAddress(rcVisardIP)) { throw invalid_argument("Given IP address is not a valid address: " + rcVisardIP); } // initial connection to rc_visard and get streams, i.e. do get request on // respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/datastreams"}; auto get = cpr::Get(url, cpr::Timeout{_timeoutCurl}); handleCPRResponse(get); // parse text of response into json object auto j = json::parse(get.text); for (const auto& stream : j) { _availStreams.push_back(stream["name"]); _protobufMap[stream["name"]] = stream["protobuf"]; } } RemoteInterface::~RemoteInterface() { cleanUpRequestedStreams(); for (const auto& s : _reqStreams) { if (s.second.size() > 0) { cerr << "[RemoteInterface] Could not stop all previously requested" " streams of type " << s.first << " on rc_visard. Please check " "device manually" " (" << _baseUrl << "/datastreams/" << s.first << ")" " for not containing any of the following legacy streams and" " delete them otherwise, e.g. using the swagger UI (" << "http://" + _visardAddrs + "/api/swagger/)" << ": " << toString(s.second) << endl; } } } RemoteInterface::State RemoteInterface::callDynamicsService(std::string serviceName) { cpr::Url url = cpr::Url{ _baseUrl + "/nodes/rc_dynamics/services/" + serviceName}; auto response = cpr::Put(url, cpr::Timeout{_timeoutCurl}); handleCPRResponse(response); auto j = json::parse(response.text); int entered_state = j["response"]["enteredState"].get<int>(); if(entered_state < static_cast<int>(State::IDLE) or entered_state > static_cast<int>(State::RUNNING_WITH_SLAM)) { //mismatch between rc_dynamics states and states used in this class? throw invalid_state(entered_state); } return static_cast<State>(entered_state); } RemoteInterface::State RemoteInterface::restart() { return callDynamicsService("restart"); } RemoteInterface::State RemoteInterface::start() { return callDynamicsService("start"); } RemoteInterface::State RemoteInterface::startSlam() { return callDynamicsService("start_slam"); } RemoteInterface::State RemoteInterface::stop() { return callDynamicsService("stop"); } RemoteInterface::State RemoteInterface::stopSlam() { return callDynamicsService("stop_slam"); } RemoteInterface::State RemoteInterface::getState() { return callDynamicsService("getstate"); } /* Replaced by above method RemoteInterface::State RemoteInterface::getState() { // do get request on respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/nodes/rc_dynamics/services/getstate"}; auto get = cpr::Get(url, cpr::Timeout{_timeoutCurl}); handleCPRResponse(get); // parse text of response into json object auto j = json::parse(get.text); if (j["status"].get<string>() == "running") return State::RUNNING; else return State::STOPPED; } */ list<string> RemoteInterface::getAvailableStreams() { return _availStreams; } string RemoteInterface::getPbMsgTypeOfStream(const string &stream) { checkStreamTypeAvailable(stream); return _protobufMap[stream]; } list<string> RemoteInterface::getDestinationsOfStream(const string &stream) { checkStreamTypeAvailable(stream); list<string> destinations; // do get request on respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/datastreams/" + stream}; auto get = cpr::Get(url, cpr::Timeout{_timeoutCurl}); handleCPRResponse(get); // parse result as json auto j = json::parse(get.text); for (auto dest : j["destinations"]) { destinations.push_back(dest.get<string>()); } return destinations; } void RemoteInterface::addDestinationToStream(const string &stream, const string &destination) { checkStreamTypeAvailable(stream); // do put request on respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/datastreams/" + stream}; auto put = cpr::Put(url, cpr::Timeout{_timeoutCurl}, cpr::Parameters{{"destination", destination}}); handleCPRResponse(put); // keep track of added destinations _reqStreams[stream].push_back(destination); } void RemoteInterface::deleteDestinationFromStream(const string &stream, const string &destination) { checkStreamTypeAvailable(stream); // do delete request on respective url (no parameters needed for this simple service call) cpr::Url url = cpr::Url{_baseUrl + "/datastreams/" + stream}; auto del = cpr::Delete(url, cpr::Timeout{_timeoutCurl}, cpr::Parameters{{"destination", destination}}); handleCPRResponse(del); // delete destination also from list of requested streams auto& destinations = _reqStreams[stream]; auto found = find(destinations.begin(), destinations.end(), destination); if (found != destinations.end()) destinations.erase(found); } DataReceiver::Ptr RemoteInterface::createReceiverForStream(const string &stream, const string &destInterface, unsigned int destPort) { checkStreamTypeAvailable(stream); // figure out local inet address for streaming string destAddress; if (!getThisHostsIP(destAddress, _visardAddrs, destInterface)) { stringstream msg; msg << "Could not infer a valid IP address " "for this host as the destination of the stream! " "Given network interface specification was '" << destInterface << "'."; throw invalid_argument(msg.str()); } // create data receiver with port as specified DataReceiver::Ptr receiver = TrackedDataReceiver::create(destAddress, destPort, stream, shared_from_this()); // do REST-API call requesting a UDP stream from rc_visard device string destination = destAddress + ":" + to_string(destPort); addDestinationToStream(stream, destination); // waiting for first message; we set a long timeout for receiving data unsigned int initialTimeOut = 5000; receiver->setTimeout(initialTimeOut); if (!receiver->receive(_protobufMap[stream])) { throw UnexpectedReceiveTimeout(initialTimeOut); // stringstream msg; // msg << "Did not receive any data within the last " // << initialTimeOut << " ms. " // << "Either rc_visard does not seem to send the data properly " // "(is rc_dynamics module running?) or you seem to have serious " // "network/connection problems!"; // throw runtime_error(msg.str()); } // stream established, prepare everything for normal pose receiving receiver->setTimeout(100); return receiver; } void RemoteInterface::cleanUpRequestedStreams() { // for each stream type check currently running streams on rc_visard device for (auto const &s : _reqStreams) { // get a list of currently active streams of this type on rc_visard device list<string> rcVisardsActiveStreams; try { rcVisardsActiveStreams = getDestinationsOfStream(s.first); } catch (exception &e) { cerr << "[RemoteInterface] Could not get list of active " << s.first << " streams for cleaning up previously requested streams: " << e.what() << endl; continue; } // try to stop all previously requested streams of this type for (auto activeStream : rcVisardsActiveStreams) { auto found = find(s.second.begin(), s.second.end(), activeStream); if (found != s.second.end()) { try { deleteDestinationFromStream(s.first, activeStream); } catch (exception &e) { cerr << "[RemoteInterface] Could not delete destination " << activeStream << " from " << s.first << " stream: " << e.what() << endl; } } } } } void RemoteInterface::checkStreamTypeAvailable(const string& stream) { auto found = find(_availStreams.begin(), _availStreams.end(), stream); if (found == _availStreams.end()) { stringstream msg; msg << "Stream of type '" << stream << "' is not available on rc_visard " << _visardAddrs; throw invalid_argument(msg.str()); } } } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// Reaper /// /// Copyright (c) 2015-2017 Thibault Schueller /// This file is distributed under the MIT License //////////////////////////////////////////////////////////////////////////////// #include "Win32Window.h" #include "renderer/Renderer.h" namespace { LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_SIZE: case WM_EXITSIZEMOVE: PostMessage(hWnd, WM_USER + 1, wParam, lParam); break; case WM_KEYDOWN: case WM_CLOSE: PostMessage(hWnd, WM_USER + 2, wParam, lParam); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } } #define REAPER_WINDOW_INFO "Reaper" Win32Window::Win32Window(const WindowCreationDescriptor& creationInfo) : Instance() , Handle() { Instance = GetModuleHandle(nullptr); // Register window class WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = Instance; wcex.hIcon = nullptr; wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = nullptr; wcex.lpszClassName = REAPER_WINDOW_INFO; wcex.hIconSm = nullptr; if (!RegisterClassEx(&wcex)) { AssertUnreachable(); return; } constexpr u32 DefaultX = 40; constexpr u32 DefaultY = DefaultX; RECT rect; rect.left = DefaultX; rect.top = DefaultY; rect.right = creationInfo.width + DefaultX; rect.bottom = creationInfo.height + DefaultY; const DWORD style = WS_OVERLAPPEDWINDOW; const HWND parent = nullptr; const HMENU menu = nullptr; const BOOL hasMenu = (menu == nullptr ? FALSE : TRUE); // Adjust rect to account for window decorations so we get the desired resolution Assert(AdjustWindowRect(&rect, style, hasMenu) != FALSE); const LPVOID param = nullptr; // Create window Handle = CreateWindow(REAPER_WINDOW_INFO, creationInfo.title, style, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, parent, menu, Instance, param); Assert(Handle != nullptr); } Win32Window::~Win32Window() { if (Handle) DestroyWindow(Handle); if (Instance) UnregisterClass(REAPER_WINDOW_INFO, Instance); } bool Win32Window::renderLoop(AbstractRenderer* renderer) { // Display window ShowWindow(Handle, SW_SHOWNORMAL); UpdateWindow(Handle); // Main message loop MSG message; bool loop = true; bool resize = false; while (loop) { if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { // Process events switch (message.message) { // Resize case WM_USER + 1: resize = true; break; // Close case WM_USER + 2: loop = false; break; } TranslateMessage(&message); DispatchMessage(&message); } else { // Draw if (resize) { resize = false; // if( !renderer.OnWindowSizeChanged() ) { // loop = false; // } } renderer->render(); } } return true; } <commit_msg>Stronger asserts for win32 windows creation.<commit_after>//////////////////////////////////////////////////////////////////////////////// /// Reaper /// /// Copyright (c) 2015-2017 Thibault Schueller /// This file is distributed under the MIT License //////////////////////////////////////////////////////////////////////////////// #include "Win32Window.h" #include "renderer/Renderer.h" namespace { LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_SIZE: case WM_EXITSIZEMOVE: PostMessage(hWnd, WM_USER + 1, wParam, lParam); break; case WM_KEYDOWN: case WM_CLOSE: PostMessage(hWnd, WM_USER + 2, wParam, lParam); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } } #define REAPER_WINDOW_INFO "Reaper" Win32Window::Win32Window(const WindowCreationDescriptor& creationInfo) : Instance() , Handle() { Instance = GetModuleHandle(nullptr); Assert(Instance != nullptr); // Register window class WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = Instance; wcex.hIcon = nullptr; wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = nullptr; wcex.lpszClassName = REAPER_WINDOW_INFO; wcex.hIconSm = nullptr; if (!RegisterClassEx(&wcex)) { AssertUnreachable(); return; } constexpr u32 DefaultX = 40; constexpr u32 DefaultY = DefaultX; RECT rect; rect.left = DefaultX; rect.top = DefaultY; rect.right = creationInfo.width + DefaultX; rect.bottom = creationInfo.height + DefaultY; const DWORD style = WS_OVERLAPPEDWINDOW; const HWND parent = nullptr; const HMENU menu = nullptr; const BOOL hasMenu = (menu == nullptr ? FALSE : TRUE); // Adjust rect to account for window decorations so we get the desired resolution Assert(AdjustWindowRect(&rect, style, hasMenu) != FALSE); const LPVOID param = nullptr; // Create window Handle = CreateWindow(REAPER_WINDOW_INFO, creationInfo.title, style, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, parent, menu, Instance, param); Assert(Handle != nullptr); } Win32Window::~Win32Window() { if (Handle) Assert(DestroyWindow(Handle) != FALSE); if (Instance) Assert(UnregisterClass(REAPER_WINDOW_INFO, Instance) != FALSE); } bool Win32Window::renderLoop(AbstractRenderer* renderer) { // Display window ShowWindow(Handle, SW_SHOWNORMAL); UpdateWindow(Handle); // Main message loop MSG message; bool loop = true; bool resize = false; while (loop) { if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { // Process events switch (message.message) { // Resize case WM_USER + 1: resize = true; break; // Close case WM_USER + 2: loop = false; break; } TranslateMessage(&message); DispatchMessage(&message); } else { // Draw if (resize) { resize = false; // if( !renderer.OnWindowSizeChanged() ) { // loop = false; // } } renderer->render(); } } return true; } <|endoftext|>
<commit_before>#pragma once #ifndef WTL_SFMT_HPP_ #define WTL_SFMT_HPP_ #include <random> #include <limits> #define HAVE_SSE2 #define SFMT_MEXP 19937 #include "SFMT/SFMT.h" /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// namespace wtl { /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// namespace { union bits64_t { uint64_t as_uint64_t; uint32_t as_uint32_t[2]; double as_double; bits64_t(uint64_t x): as_uint64_t{x} {} bits64_t(uint32_t x, uint32_t y): as_uint32_t{x, y} {} // Use 52 bits to make double [0.0, 1.0) double as_canonical() const { bits64_t exponent_zero = (as_uint64_t >> 2) | 0x3ff0'0000'0000'0000; return exponent_zero.as_double - 1.0; } }; } class sfmt19937 { public: typedef uint32_t result_type; typedef sfmt_t state_type; static constexpr result_type min() {return 0U;} static constexpr result_type max() {return std::numeric_limits<result_type>::max();} static constexpr result_type default_seed = 5489U; // constructors explicit sfmt19937(const result_type s=default_seed) {seed(s);} explicit sfmt19937(const state_type& state): state_(state) {} sfmt19937(const sfmt19937&) = default; sfmt19937(sfmt19937&&) = default; // [0, 2^32-1] result_type operator()() { return sfmt_genrand_uint32(&state_); } // [0.0, 1.0) double canonical() { return std::generate_canonical<double, std::numeric_limits<double>::digits>(*this); } // possible implementation double _canonical() { return bits64_t(this->operator()(), this->operator()()).as_canonical(); } void seed(const result_type s) { sfmt_init_gen_rand(&state_, s); } void discard(unsigned long long n) { for (; n != 0ULL; --n) {(*this)();} } const state_type& getstate() const {return state_;} void setstate(const state_type& state) {state_ = state;} private: state_type state_; }; class sfmt19937_64 { public: typedef uint64_t result_type; typedef sfmt_t state_type; static constexpr result_type min() {return 0U;} static constexpr result_type max() {return std::numeric_limits<result_type>::max();} static constexpr result_type default_seed = 5489U; // constructors explicit sfmt19937_64(const result_type s=default_seed) {seed(s);} explicit sfmt19937_64(const state_type& state): state_(state) {} sfmt19937_64(const sfmt19937_64&) = default; sfmt19937_64(sfmt19937_64&&) = default; // [0, 2^64-1] result_type operator()() { return sfmt_genrand_uint64(&state_); } // [0.0, 1.0) double canonical() { return std::generate_canonical<double, std::numeric_limits<double>::digits>(*this); } // possible implementation double _canonical() { return bits64_t(this->operator()()).as_canonical(); } void seed(const result_type s) { sfmt_init_gen_rand(&state_, s); } void discard(unsigned long long n) { for (; n != 0ULL; --n) {(*this)();} } const state_type& getstate() const {return state_;} void setstate(const state_type& state) {state_ = state;} private: state_type state_; }; /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// inline sfmt19937& sfmt() { static sfmt19937 generator(std::random_device{}()); return generator; } inline sfmt19937_64& sfmt64() { static sfmt19937_64 generator(std::random_device{}()); return generator; } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// } // namespace wtl /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// #endif /* WTL_SFMT_HPP_ */ <commit_msg>:fire: Remove canonical() method<commit_after>#pragma once #ifndef WTL_SFMT_HPP_ #define WTL_SFMT_HPP_ #include <random> #include <limits> #define HAVE_SSE2 #define SFMT_MEXP 19937 #include "SFMT/SFMT.h" /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// namespace wtl { /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// class sfmt19937 { public: typedef uint32_t result_type; typedef sfmt_t state_type; static constexpr result_type min() {return 0U;} static constexpr result_type max() {return std::numeric_limits<result_type>::max();} static constexpr result_type default_seed = 5489U; // constructors explicit sfmt19937(const result_type s=default_seed) {seed(s);} explicit sfmt19937(const state_type& state): state_(state) {} sfmt19937(const sfmt19937&) = default; sfmt19937(sfmt19937&&) = default; // [0, 2^32-1] result_type operator()() { return sfmt_genrand_uint32(&state_); } void seed(const result_type s) { sfmt_init_gen_rand(&state_, s); } void discard(unsigned long long n) { for (; n != 0ULL; --n) {(*this)();} } const state_type& getstate() const {return state_;} void setstate(const state_type& state) {state_ = state;} private: state_type state_; }; class sfmt19937_64 { public: typedef uint64_t result_type; typedef sfmt_t state_type; static constexpr result_type min() {return 0U;} static constexpr result_type max() {return std::numeric_limits<result_type>::max();} static constexpr result_type default_seed = 5489U; // constructors explicit sfmt19937_64(const result_type s=default_seed) {seed(s);} explicit sfmt19937_64(const state_type& state): state_(state) {} sfmt19937_64(const sfmt19937_64&) = default; sfmt19937_64(sfmt19937_64&&) = default; // [0, 2^64-1] result_type operator()() { return sfmt_genrand_uint64(&state_); } void seed(const result_type s) { sfmt_init_gen_rand(&state_, s); } void discard(unsigned long long n) { for (; n != 0ULL; --n) {(*this)();} } const state_type& getstate() const {return state_;} void setstate(const state_type& state) {state_ = state;} private: state_type state_; }; /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// inline sfmt19937& sfmt() { static sfmt19937 generator(std::random_device{}()); return generator; } inline sfmt19937_64& sfmt64() { static sfmt19937_64 generator(std::random_device{}()); return generator; } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// } // namespace wtl /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// #endif /* WTL_SFMT_HPP_ */ <|endoftext|>
<commit_before>/* * GreyscaleLuminanceSource.cpp * zxing * * Copyright 2010 ZXing authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <zxing/common/GreyscaleLuminanceSource.h> #include <zxing/common/GreyscaleRotatedLuminanceSource.h> #include <zxing/common/IllegalArgumentException.h> namespace zxing { GreyscaleLuminanceSource::GreyscaleLuminanceSource(unsigned char* greyData, int dataWidth, int dataHeight, int left, int top, int width, int height) : greyData_(greyData), dataWidth_(dataWidth), dataHeight_(dataHeight), left_(left), top_(top), width_(width), height_(height) { if (left + width > dataWidth || top + height > dataHeight || top < 0 || left < 0) { throw IllegalArgumentException("Crop rectangle does not fit within image data."); } } unsigned char* GreyscaleLuminanceSource::getRow(int y, unsigned char* row) { if (y < 0 || y >= this->getHeight()) { throw IllegalArgumentException("Requested row is outside the image: " + y); } int width = getWidth(); // TODO(flyashi): determine if row has enough size. if (row == NULL) { row = new unsigned char[width_]; } int offset = (y + top_) * dataWidth_ + left_; memcpy(row, &greyData_[offset], width); return row; } unsigned char* GreyscaleLuminanceSource::getMatrix() { if (left_ != 0 || top_ != 0 || dataWidth_ != width_ || dataHeight_ != height_) { unsigned char* cropped = new unsigned char[width_ * height_]; for (int row = 0; row < height_; row++) { memcpy(cropped + row * width_, greyData_ + (top_ + row) * dataWidth_ + left_, width_); } return cropped; } return greyData_; } Ref<LuminanceSource> GreyscaleLuminanceSource::rotateCounterClockwise() { // Intentionally flip the left, top, width, and height arguments as needed. dataWidth and // dataHeight are always kept unrotated. return Ref<LuminanceSource> (new GreyscaleRotatedLuminanceSource(greyData_, dataWidth_, dataHeight_, top_, left_, height_, width_)); } } /* namespace */ <commit_msg>Fixed the double delete problem remaining in issue 503.<commit_after>/* * GreyscaleLuminanceSource.cpp * zxing * * Copyright 2010 ZXing authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <zxing/common/GreyscaleLuminanceSource.h> #include <zxing/common/GreyscaleRotatedLuminanceSource.h> #include <zxing/common/IllegalArgumentException.h> namespace zxing { GreyscaleLuminanceSource::GreyscaleLuminanceSource(unsigned char* greyData, int dataWidth, int dataHeight, int left, int top, int width, int height) : greyData_(greyData), dataWidth_(dataWidth), dataHeight_(dataHeight), left_(left), top_(top), width_(width), height_(height) { if (left + width > dataWidth || top + height > dataHeight || top < 0 || left < 0) { throw IllegalArgumentException("Crop rectangle does not fit within image data."); } } unsigned char* GreyscaleLuminanceSource::getRow(int y, unsigned char* row) { if (y < 0 || y >= this->getHeight()) { throw IllegalArgumentException("Requested row is outside the image: " + y); } int width = getWidth(); // TODO(flyashi): determine if row has enough size. if (row == NULL) { row = new unsigned char[width_]; } int offset = (y + top_) * dataWidth_ + left_; memcpy(row, &greyData_[offset], width); return row; } unsigned char* GreyscaleLuminanceSource::getMatrix() { int size = width_ * height_; unsigned char* result = new unsigned char[size]; if (left_ == 0 && top_ == 0 && dataWidth_ == width_ && dataHeight_ == height_) { memcpy(result, greyData_, size); } else { for (int row = 0; row < height_; row++) { memcpy(result + row * width_, greyData_ + (top_ + row) * dataWidth_ + left_, width_); } } return result; } Ref<LuminanceSource> GreyscaleLuminanceSource::rotateCounterClockwise() { // Intentionally flip the left, top, width, and height arguments as needed. dataWidth and // dataHeight are always kept unrotated. return Ref<LuminanceSource> (new GreyscaleRotatedLuminanceSource(greyData_, dataWidth_, dataHeight_, top_, left_, height_, width_)); } } /* namespace */ <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/AbstractMessageRouter.h" #include <cassert> #include <functional> #include <boost/asio/io_service.hpp> #include "joynr/IMessagingStub.h" #include "joynr/IMessagingStubFactory.h" #include "joynr/ImmutableMessage.h" #include "joynr/IMulticastAddressCalculator.h" #include "joynr/InProcessMessagingAddress.h" #include "joynr/Message.h" #include "joynr/MulticastReceiverDirectory.h" #include "joynr/access-control/IAccessController.h" #include "joynr/exceptions/JoynrException.h" #include "joynr/system/RoutingTypes/Address.h" #include "joynr/system/RoutingTypes/BrowserAddress.h" #include "joynr/system/RoutingTypes/ChannelAddress.h" #include "joynr/system/RoutingTypes/CommonApiDbusAddress.h" #include "joynr/system/RoutingTypes/MqttAddress.h" #include "joynr/system/RoutingTypes/WebSocketAddress.h" #include "joynr/system/RoutingTypes/WebSocketClientAddress.h" namespace joynr { INIT_LOGGER(AbstractMessageRouter); //------ AbstractMessageRouter --------------------------------------------------------- AbstractMessageRouter::AbstractMessageRouter( std::shared_ptr<IMessagingStubFactory> messagingStubFactory, boost::asio::io_service& ioService, std::unique_ptr<IMulticastAddressCalculator> addressCalculator, int maxThreads, std::vector<std::shared_ptr<ITransportStatus>> transportStatuses, std::unique_ptr<MessageQueue<std::string>> messageQueue, std::unique_ptr<MessageQueue<std::shared_ptr<ITransportStatus>>> transportNotAvailableQueue) : routingTable("AbstractMessageRouter-RoutingTable", ioService, std::bind(&AbstractMessageRouter::routingTableSaveFilterFunc, this, std::placeholders::_1)), routingTableLock(), multicastReceiverDirectory(), messagingStubFactory(std::move(messagingStubFactory)), messageScheduler(maxThreads, "AbstractMessageRouter", ioService), messageQueue(std::move(messageQueue)), transportNotAvailableQueue(std::move(transportNotAvailableQueue)), routingTableFileName(), addressCalculator(std::move(addressCalculator)), messageQueueCleanerTimer(ioService), messageQueueCleanerTimerPeriodMs(std::chrono::milliseconds(1000)), transportStatuses(std::move(transportStatuses)) { activateMessageCleanerTimer(); registerTransportStatusCallbacks(); } AbstractMessageRouter::~AbstractMessageRouter() { messageQueueCleanerTimer.cancel(); messageScheduler.shutdown(); } bool AbstractMessageRouter::routingTableSaveFilterFunc(std::shared_ptr<RoutingEntry> routingEntry) { const auto destAddress = routingEntry->address; const joynr::InProcessMessagingAddress* inprocessAddress = dynamic_cast<const joynr::InProcessMessagingAddress*>(destAddress.get()); return inprocessAddress == nullptr; } void AbstractMessageRouter::addProvisionedNextHop( std::string participantId, std::shared_ptr<const joynr::system::RoutingTypes::Address> address, bool isGloballyVisible) { assert(address); const auto routingEntry = std::make_shared<RoutingEntry>(std::move(address), isGloballyVisible); addToRoutingTable(participantId, std::move(routingEntry)); } AbstractMessageRouter::AddressUnorderedSet AbstractMessageRouter::lookupAddresses( const std::unordered_set<std::string>& participantIds) { AbstractMessageRouter::AddressUnorderedSet addresses; std::shared_ptr<const joynr::system::RoutingTypes::Address> destAddress; for (const auto& participantId : participantIds) { const auto routingEntry = routingTable.lookup(participantId); if (routingEntry) { destAddress = routingEntry->address; addresses.insert(destAddress); } } assert(addresses.size() <= participantIds.size()); return addresses; } AbstractMessageRouter::AddressUnorderedSet AbstractMessageRouter::getDestinationAddresses( const ImmutableMessage& message) { AbstractMessageRouter::AddressUnorderedSet addresses; if (message.getType() == Message::VALUE_MESSAGE_TYPE_MULTICAST()) { const std::string& multicastId = message.getRecipient(); // lookup local multicast receivers std::unordered_set<std::string> multicastReceivers = multicastReceiverDirectory.getReceivers(multicastId); addresses = lookupAddresses(multicastReceivers); // add global transport address if message is NOT received from global // AND provider is globally visible if (!message.isReceivedFromGlobal() && addressCalculator && publishToGlobal(message)) { std::shared_ptr<const joynr::system::RoutingTypes::Address> globalTransport = addressCalculator->compute(message); if (globalTransport) { addresses.insert(std::move(globalTransport)); } } } else { const std::string& destinationPartId = message.getRecipient(); const auto routingEntry = routingTable.lookup(destinationPartId); if (routingEntry) { addresses.insert(routingEntry->address); } } return addresses; } void AbstractMessageRouter::checkExpiryDate(const ImmutableMessage& message) { JoynrTimePoint now = std::chrono::time_point_cast<std::chrono::milliseconds>( std::chrono::system_clock::now()); if (now > message.getExpiryDate()) { std::string errorMessage("Received expired message. Dropping the message (ID: " + message.getId() + ")."); JOYNR_LOG_WARN(logger, errorMessage); throw exceptions::JoynrMessageNotSentException(errorMessage); } } void AbstractMessageRouter::registerGlobalRoutingEntryIfRequired(const ImmutableMessage& message) { if (!message.isReceivedFromGlobal()) { return; } const std::string& messageType = message.getType(); if (messageType == Message::VALUE_MESSAGE_TYPE_REQUEST() || messageType == Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST() || messageType == Message::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST() || messageType == Message::VALUE_MESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST()) { boost::optional<std::string> optionalReplyTo = message.getReplyTo(); if (!optionalReplyTo) { std::string errorMessage("message " + message.getId() + " did not contain replyTo header, discarding"); JOYNR_LOG_ERROR(logger, errorMessage); throw exceptions::JoynrMessageNotSentException(errorMessage); } const std::string& replyTo = *optionalReplyTo; try { using system::RoutingTypes::Address; std::shared_ptr<const Address> address; joynr::serializer::deserializeFromJson(address, replyTo); // because the message is received via global transport (isGloballyVisible=true), // isGloballyVisible must be true const bool isGloballyVisible = true; addNextHop(message.getSender(), address, isGloballyVisible); } catch (const std::invalid_argument& e) { std::string errorMessage("could not deserialize Address from " + replyTo + " - error: " + e.what()); JOYNR_LOG_FATAL(logger, errorMessage); // do not try to route the message if address is not valid throw exceptions::JoynrMessageNotSentException(errorMessage); } } } void AbstractMessageRouter::route(std::shared_ptr<ImmutableMessage> message, std::uint32_t tryCount) { assert(messagingStubFactory); assert(message); checkExpiryDate(*message); routeInternal(std::move(message), tryCount); } void AbstractMessageRouter::sendMessages( const std::string& destinationPartId, std::shared_ptr<const joynr::system::RoutingTypes::Address> address) { while (true) { // We have to check all the time whether the messaging stub is still available because // it will be deleted if a disconnect occurs (this may happen while this method // is being executed). auto messagingStub = messagingStubFactory->create(address); if (messagingStub == nullptr) { break; } std::unique_ptr<MessageQueueItem> item(messageQueue->getNextMessageFor(destinationPartId)); if (!item) { break; } try { const std::uint32_t tryCount = 0; messageScheduler.schedule( new MessageRunnable( item->getContent(), std::move(messagingStub), address, *this, tryCount), std::chrono::milliseconds(0)); } catch (const exceptions::JoynrMessageNotSentException& e) { JOYNR_LOG_ERROR(logger, "Message with Id {} could not be sent. Error: {}", item->getContent()->getId(), e.getMessage()); } } } void AbstractMessageRouter::scheduleMessage( std::shared_ptr<ImmutableMessage> message, std::shared_ptr<const joynr::system::RoutingTypes::Address> destAddress, std::uint32_t tryCount, std::chrono::milliseconds delay) { for (const auto& transportStatus : transportStatuses) { if (transportStatus->isReponsibleFor(destAddress)) { if (!transportStatus->isAvailable()) { JOYNR_LOG_TRACE(logger, "Transport not available. Message queued: {}", message->toLogMessage()); transportNotAvailableQueue->queueMessage(transportStatus, std::move(message)); return; } } } auto stub = messagingStubFactory->create(destAddress); if (stub) { messageScheduler.schedule(new MessageRunnable(std::move(message), std::move(stub), std::move(destAddress), *this, tryCount), delay); } else { JOYNR_LOG_WARN( logger, "Message with id {} could not be send to {}. Stub creation failed. => Queueing " "message.", message->getId(), destAddress->toString()); // save the message for later delivery queueMessage(std::move(message)); } } void AbstractMessageRouter::activateMessageCleanerTimer() { messageQueueCleanerTimer.expiresFromNow(messageQueueCleanerTimerPeriodMs); messageQueueCleanerTimer.asyncWait(std::bind( &AbstractMessageRouter::onMessageCleanerTimerExpired, this, std::placeholders::_1)); } void AbstractMessageRouter::registerTransportStatusCallbacks() { for (auto& transportStatus : transportStatuses) { transportStatus->setAvailabilityChangedCallback([this, transportStatus](bool isAvailable) { if (isAvailable) { rescheduleQueuedMessagesForTransport(transportStatus); } }); } } void AbstractMessageRouter::rescheduleQueuedMessagesForTransport( std::shared_ptr<ITransportStatus> transportStatus) { while (auto nextImmutableMessage = transportNotAvailableQueue->getNextMessageFor(transportStatus)) { route(nextImmutableMessage->getContent()); } } void AbstractMessageRouter::onMessageCleanerTimerExpired(const boost::system::error_code& errorCode) { if (!errorCode) { messageQueue->removeOutdatedMessages(); activateMessageCleanerTimer(); } else if (errorCode != boost::system::errc::operation_canceled) { JOYNR_LOG_ERROR(logger, "Failed to schedule timer to remove outdated messages: {}", errorCode.message()); } } void AbstractMessageRouter::queueMessage(std::shared_ptr<ImmutableMessage> message) { JOYNR_LOG_TRACE(logger, "message queued: {}", message->toLogMessage()); std::string recipient = message->getRecipient(); messageQueue->queueMessage(std::move(recipient), std::move(message)); } void AbstractMessageRouter::loadRoutingTable(std::string fileName) { // always update reference file if (fileName != routingTableFileName) { routingTableFileName = std::move(fileName); } if (!joynr::util::fileExists(routingTableFileName)) { return; } WriteLocker lock(routingTableLock); try { joynr::serializer::deserializeFromJson( routingTable, joynr::util::loadStringFromFile(routingTableFileName)); } catch (const std::runtime_error& ex) { JOYNR_LOG_ERROR(logger, ex.what()); } catch (const std::invalid_argument& ex) { JOYNR_LOG_ERROR(logger, "could not deserialize from JSON: {}", ex.what()); } } void AbstractMessageRouter::saveRoutingTable() { WriteLocker lock(routingTableLock); try { joynr::util::saveStringToFile( routingTableFileName, joynr::serializer::serializeToJson(routingTable)); } catch (const std::runtime_error& ex) { JOYNR_LOG_INFO(logger, ex.what()); } } void AbstractMessageRouter::addToRoutingTable(std::string participantId, std::shared_ptr<RoutingEntry> routingEntry) { { WriteLocker lock(routingTableLock); routingTable.add(participantId, std::move(routingEntry)); } saveRoutingTable(); } /** * IMPLEMENTATION of MessageRunnable class */ INIT_LOGGER(MessageRunnable); MessageRunnable::MessageRunnable( std::shared_ptr<ImmutableMessage> message, std::shared_ptr<IMessagingStub> messagingStub, std::shared_ptr<const joynr::system::RoutingTypes::Address> destAddress, AbstractMessageRouter& messageRouter, std::uint32_t tryCount) : Runnable(true), ObjectWithDecayTime(message->getExpiryDate()), message(message), messagingStub(messagingStub), destAddress(destAddress), messageRouter(messageRouter), tryCount(tryCount) { } void MessageRunnable::shutdown() { } void MessageRunnable::run() { if (!isExpired()) { // TODO is it safe to capture (this) here? rather capture members by value! auto onFailure = [this](const exceptions::JoynrRuntimeException& e) { try { exceptions::JoynrDelayMessageException& delayException = dynamic_cast<exceptions::JoynrDelayMessageException&>( const_cast<exceptions::JoynrRuntimeException&>(e)); std::chrono::milliseconds delay = delayException.getDelayMs(); JOYNR_LOG_TRACE(logger, "Rescheduling message after error: messageId: {}, new delay {}ms, " "reason: {}", message->getId(), delay.count(), e.getMessage()); messageRouter.scheduleMessage(message, destAddress, tryCount + 1, delay); } catch (const std::bad_cast&) { JOYNR_LOG_ERROR(logger, "Message with ID {} could not be sent! reason: {}", message->getId(), e.getMessage()); } }; messagingStub->transmit(message, onFailure); } else { JOYNR_LOG_ERROR(logger, "Message with ID {} expired: dropping!", message->getId()); } } } // namespace joynr <commit_msg>[C++] preventing acccess to writing to the disk for inprocess messaging address<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/AbstractMessageRouter.h" #include <cassert> #include <functional> #include <boost/asio/io_service.hpp> #include "joynr/IMessagingStub.h" #include "joynr/IMessagingStubFactory.h" #include "joynr/ImmutableMessage.h" #include "joynr/IMulticastAddressCalculator.h" #include "joynr/InProcessMessagingAddress.h" #include "joynr/Message.h" #include "joynr/MulticastReceiverDirectory.h" #include "joynr/access-control/IAccessController.h" #include "joynr/exceptions/JoynrException.h" #include "joynr/system/RoutingTypes/Address.h" #include "joynr/system/RoutingTypes/BrowserAddress.h" #include "joynr/system/RoutingTypes/ChannelAddress.h" #include "joynr/system/RoutingTypes/CommonApiDbusAddress.h" #include "joynr/system/RoutingTypes/MqttAddress.h" #include "joynr/system/RoutingTypes/WebSocketAddress.h" #include "joynr/system/RoutingTypes/WebSocketClientAddress.h" namespace joynr { INIT_LOGGER(AbstractMessageRouter); //------ AbstractMessageRouter --------------------------------------------------------- AbstractMessageRouter::AbstractMessageRouter( std::shared_ptr<IMessagingStubFactory> messagingStubFactory, boost::asio::io_service& ioService, std::unique_ptr<IMulticastAddressCalculator> addressCalculator, int maxThreads, std::vector<std::shared_ptr<ITransportStatus>> transportStatuses, std::unique_ptr<MessageQueue<std::string>> messageQueue, std::unique_ptr<MessageQueue<std::shared_ptr<ITransportStatus>>> transportNotAvailableQueue) : routingTable("AbstractMessageRouter-RoutingTable", ioService, std::bind(&AbstractMessageRouter::routingTableSaveFilterFunc, this, std::placeholders::_1)), routingTableLock(), multicastReceiverDirectory(), messagingStubFactory(std::move(messagingStubFactory)), messageScheduler(maxThreads, "AbstractMessageRouter", ioService), messageQueue(std::move(messageQueue)), transportNotAvailableQueue(std::move(transportNotAvailableQueue)), routingTableFileName(), addressCalculator(std::move(addressCalculator)), messageQueueCleanerTimer(ioService), messageQueueCleanerTimerPeriodMs(std::chrono::milliseconds(1000)), transportStatuses(std::move(transportStatuses)) { activateMessageCleanerTimer(); registerTransportStatusCallbacks(); } AbstractMessageRouter::~AbstractMessageRouter() { messageQueueCleanerTimer.cancel(); messageScheduler.shutdown(); } bool AbstractMessageRouter::routingTableSaveFilterFunc(std::shared_ptr<RoutingEntry> routingEntry) { if (!routingEntry) { return false; } const auto destAddress = routingEntry->address; const joynr::InProcessMessagingAddress* inprocessAddress = dynamic_cast<const joynr::InProcessMessagingAddress*>(destAddress.get()); return inprocessAddress == nullptr; } void AbstractMessageRouter::addProvisionedNextHop( std::string participantId, std::shared_ptr<const joynr::system::RoutingTypes::Address> address, bool isGloballyVisible) { assert(address); const auto routingEntry = std::make_shared<RoutingEntry>(std::move(address), isGloballyVisible); addToRoutingTable(participantId, std::move(routingEntry)); } AbstractMessageRouter::AddressUnorderedSet AbstractMessageRouter::lookupAddresses( const std::unordered_set<std::string>& participantIds) { AbstractMessageRouter::AddressUnorderedSet addresses; std::shared_ptr<const joynr::system::RoutingTypes::Address> destAddress; for (const auto& participantId : participantIds) { const auto routingEntry = routingTable.lookup(participantId); if (routingEntry) { destAddress = routingEntry->address; addresses.insert(destAddress); } } assert(addresses.size() <= participantIds.size()); return addresses; } AbstractMessageRouter::AddressUnorderedSet AbstractMessageRouter::getDestinationAddresses( const ImmutableMessage& message) { AbstractMessageRouter::AddressUnorderedSet addresses; if (message.getType() == Message::VALUE_MESSAGE_TYPE_MULTICAST()) { const std::string& multicastId = message.getRecipient(); // lookup local multicast receivers std::unordered_set<std::string> multicastReceivers = multicastReceiverDirectory.getReceivers(multicastId); addresses = lookupAddresses(multicastReceivers); // add global transport address if message is NOT received from global // AND provider is globally visible if (!message.isReceivedFromGlobal() && addressCalculator && publishToGlobal(message)) { std::shared_ptr<const joynr::system::RoutingTypes::Address> globalTransport = addressCalculator->compute(message); if (globalTransport) { addresses.insert(std::move(globalTransport)); } } } else { const std::string& destinationPartId = message.getRecipient(); const auto routingEntry = routingTable.lookup(destinationPartId); if (routingEntry) { addresses.insert(routingEntry->address); } } return addresses; } void AbstractMessageRouter::checkExpiryDate(const ImmutableMessage& message) { JoynrTimePoint now = std::chrono::time_point_cast<std::chrono::milliseconds>( std::chrono::system_clock::now()); if (now > message.getExpiryDate()) { std::string errorMessage("Received expired message. Dropping the message (ID: " + message.getId() + ")."); JOYNR_LOG_WARN(logger, errorMessage); throw exceptions::JoynrMessageNotSentException(errorMessage); } } void AbstractMessageRouter::registerGlobalRoutingEntryIfRequired(const ImmutableMessage& message) { if (!message.isReceivedFromGlobal()) { return; } const std::string& messageType = message.getType(); if (messageType == Message::VALUE_MESSAGE_TYPE_REQUEST() || messageType == Message::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST() || messageType == Message::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST() || messageType == Message::VALUE_MESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST()) { boost::optional<std::string> optionalReplyTo = message.getReplyTo(); if (!optionalReplyTo) { std::string errorMessage("message " + message.getId() + " did not contain replyTo header, discarding"); JOYNR_LOG_ERROR(logger, errorMessage); throw exceptions::JoynrMessageNotSentException(errorMessage); } const std::string& replyTo = *optionalReplyTo; try { using system::RoutingTypes::Address; std::shared_ptr<const Address> address; joynr::serializer::deserializeFromJson(address, replyTo); // because the message is received via global transport (isGloballyVisible=true), // isGloballyVisible must be true const bool isGloballyVisible = true; addNextHop(message.getSender(), address, isGloballyVisible); } catch (const std::invalid_argument& e) { std::string errorMessage("could not deserialize Address from " + replyTo + " - error: " + e.what()); JOYNR_LOG_FATAL(logger, errorMessage); // do not try to route the message if address is not valid throw exceptions::JoynrMessageNotSentException(errorMessage); } } } void AbstractMessageRouter::route(std::shared_ptr<ImmutableMessage> message, std::uint32_t tryCount) { assert(messagingStubFactory); assert(message); checkExpiryDate(*message); routeInternal(std::move(message), tryCount); } void AbstractMessageRouter::sendMessages( const std::string& destinationPartId, std::shared_ptr<const joynr::system::RoutingTypes::Address> address) { while (true) { // We have to check all the time whether the messaging stub is still available because // it will be deleted if a disconnect occurs (this may happen while this method // is being executed). auto messagingStub = messagingStubFactory->create(address); if (messagingStub == nullptr) { break; } std::unique_ptr<MessageQueueItem> item(messageQueue->getNextMessageFor(destinationPartId)); if (!item) { break; } try { const std::uint32_t tryCount = 0; messageScheduler.schedule( new MessageRunnable( item->getContent(), std::move(messagingStub), address, *this, tryCount), std::chrono::milliseconds(0)); } catch (const exceptions::JoynrMessageNotSentException& e) { JOYNR_LOG_ERROR(logger, "Message with Id {} could not be sent. Error: {}", item->getContent()->getId(), e.getMessage()); } } } void AbstractMessageRouter::scheduleMessage( std::shared_ptr<ImmutableMessage> message, std::shared_ptr<const joynr::system::RoutingTypes::Address> destAddress, std::uint32_t tryCount, std::chrono::milliseconds delay) { for (const auto& transportStatus : transportStatuses) { if (transportStatus->isReponsibleFor(destAddress)) { if (!transportStatus->isAvailable()) { JOYNR_LOG_TRACE(logger, "Transport not available. Message queued: {}", message->toLogMessage()); transportNotAvailableQueue->queueMessage(transportStatus, std::move(message)); return; } } } auto stub = messagingStubFactory->create(destAddress); if (stub) { messageScheduler.schedule(new MessageRunnable(std::move(message), std::move(stub), std::move(destAddress), *this, tryCount), delay); } else { JOYNR_LOG_WARN( logger, "Message with id {} could not be send to {}. Stub creation failed. => Queueing " "message.", message->getId(), destAddress->toString()); // save the message for later delivery queueMessage(std::move(message)); } } void AbstractMessageRouter::activateMessageCleanerTimer() { messageQueueCleanerTimer.expiresFromNow(messageQueueCleanerTimerPeriodMs); messageQueueCleanerTimer.asyncWait(std::bind( &AbstractMessageRouter::onMessageCleanerTimerExpired, this, std::placeholders::_1)); } void AbstractMessageRouter::registerTransportStatusCallbacks() { for (auto& transportStatus : transportStatuses) { transportStatus->setAvailabilityChangedCallback([this, transportStatus](bool isAvailable) { if (isAvailable) { rescheduleQueuedMessagesForTransport(transportStatus); } }); } } void AbstractMessageRouter::rescheduleQueuedMessagesForTransport( std::shared_ptr<ITransportStatus> transportStatus) { while (auto nextImmutableMessage = transportNotAvailableQueue->getNextMessageFor(transportStatus)) { route(nextImmutableMessage->getContent()); } } void AbstractMessageRouter::onMessageCleanerTimerExpired(const boost::system::error_code& errorCode) { if (!errorCode) { messageQueue->removeOutdatedMessages(); activateMessageCleanerTimer(); } else if (errorCode != boost::system::errc::operation_canceled) { JOYNR_LOG_ERROR(logger, "Failed to schedule timer to remove outdated messages: {}", errorCode.message()); } } void AbstractMessageRouter::queueMessage(std::shared_ptr<ImmutableMessage> message) { JOYNR_LOG_TRACE(logger, "message queued: {}", message->toLogMessage()); std::string recipient = message->getRecipient(); messageQueue->queueMessage(std::move(recipient), std::move(message)); } void AbstractMessageRouter::loadRoutingTable(std::string fileName) { // always update reference file if (fileName != routingTableFileName) { routingTableFileName = std::move(fileName); } if (!joynr::util::fileExists(routingTableFileName)) { return; } WriteLocker lock(routingTableLock); try { joynr::serializer::deserializeFromJson( routingTable, joynr::util::loadStringFromFile(routingTableFileName)); } catch (const std::runtime_error& ex) { JOYNR_LOG_ERROR(logger, ex.what()); } catch (const std::invalid_argument& ex) { JOYNR_LOG_ERROR(logger, "could not deserialize from JSON: {}", ex.what()); } } void AbstractMessageRouter::saveRoutingTable() { WriteLocker lock(routingTableLock); try { joynr::util::saveStringToFile( routingTableFileName, joynr::serializer::serializeToJson(routingTable)); } catch (const std::runtime_error& ex) { JOYNR_LOG_INFO(logger, ex.what()); } } void AbstractMessageRouter::addToRoutingTable(std::string participantId, std::shared_ptr<RoutingEntry> routingEntry) { { WriteLocker lock(routingTableLock); routingTable.add(participantId, routingEntry); } if (routingTableSaveFilterFunc(std::move(routingEntry))) { // preventing acccess to writing to the disk for inprocess messaging address saveRoutingTable(); } } /** * IMPLEMENTATION of MessageRunnable class */ INIT_LOGGER(MessageRunnable); MessageRunnable::MessageRunnable( std::shared_ptr<ImmutableMessage> message, std::shared_ptr<IMessagingStub> messagingStub, std::shared_ptr<const joynr::system::RoutingTypes::Address> destAddress, AbstractMessageRouter& messageRouter, std::uint32_t tryCount) : Runnable(true), ObjectWithDecayTime(message->getExpiryDate()), message(message), messagingStub(messagingStub), destAddress(destAddress), messageRouter(messageRouter), tryCount(tryCount) { } void MessageRunnable::shutdown() { } void MessageRunnable::run() { if (!isExpired()) { // TODO is it safe to capture (this) here? rather capture members by value! auto onFailure = [this](const exceptions::JoynrRuntimeException& e) { try { exceptions::JoynrDelayMessageException& delayException = dynamic_cast<exceptions::JoynrDelayMessageException&>( const_cast<exceptions::JoynrRuntimeException&>(e)); std::chrono::milliseconds delay = delayException.getDelayMs(); JOYNR_LOG_TRACE(logger, "Rescheduling message after error: messageId: {}, new delay {}ms, " "reason: {}", message->getId(), delay.count(), e.getMessage()); messageRouter.scheduleMessage(message, destAddress, tryCount + 1, delay); } catch (const std::bad_cast&) { JOYNR_LOG_ERROR(logger, "Message with ID {} could not be sent! reason: {}", message->getId(), e.getMessage()); } }; messagingStub->transmit(message, onFailure); } else { JOYNR_LOG_ERROR(logger, "Message with ID {} expired: dropping!", message->getId()); } } } // namespace joynr <|endoftext|>
<commit_before>/* Copyright (c) 2009-2013, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/allocator.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #if defined TORRENT_BEOS #include <kernel/OS.h> #include <stdlib.h> // malloc/free #elif !defined TORRENT_WINDOWS #include <stdlib.h> // valloc/free #include <unistd.h> // _SC_PAGESIZE #endif #if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS #include <malloc.h> // memalign and _aligned_malloc #include <stdlib.h> // _aligned_malloc on mingw #endif #ifdef TORRENT_WINDOWS // windows.h must be included after stdlib.h under mingw #include <windows.h> #endif #ifdef TORRENT_MINGW #define _aligned_malloc __mingw_aligned_malloc #define _aligned_free __mingw_aligned_free #endif #ifdef TORRENT_DEBUG_BUFFERS #ifndef TORRENT_WINDOWS #include <sys/mman.h> #endif #include "libtorrent/size_type.hpp" struct alloc_header { libtorrent::size_type size; int magic; char stack[3072]; }; #endif namespace libtorrent { int page_size() { static int s = 0; if (s != 0) return s; #ifdef TORRENT_WINDOWS SYSTEM_INFO si; GetSystemInfo(&si); s = si.dwPageSize; #elif defined TORRENT_BEOS s = B_PAGE_SIZE; #else s = sysconf(_SC_PAGESIZE); #endif // assume the page size is 4 kiB if we // fail to query it if (s <= 0) s = 4096; return s; } char* page_aligned_allocator::malloc(size_type bytes) { TORRENT_ASSERT(bytes >= page_size()); #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); int num_pages = (bytes + (page-1)) / page + 2; char* ret = (char*)valloc(num_pages * page); // make the two surrounding pages non-readable and -writable alloc_header* h = (alloc_header*)ret; h->size = bytes; h->magic = 0x1337; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #endif mprotect(ret, page, PROT_READ); mprotect(ret + (num_pages-1) * page, page, PROT_READ); #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #endif // fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes)); return ret + page; #endif #if TORRENT_USE_POSIX_MEMALIGN void* ret; if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0; return (char*)ret; #elif TORRENT_USE_MEMALIGN return (char*)memalign(page_size(), bytes); #elif defined TORRENT_WINDOWS return (char*)_aligned_malloc(bytes, page_size()); #elif defined TORRENT_BEOS void* ret = 0; area_id id = create_area("", &ret, B_ANY_ADDRESS , (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (id < B_OK) return 0; return (char*)ret; #else return (char*)valloc(bytes); #endif } void page_aligned_allocator::free(char* const block) { #ifdef TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #define PROT_WRITE PAGE_READWRITE #endif int page = page_size(); // make the two surrounding pages non-readable and -writable mprotect(block - page, page, PROT_READ | PROT_WRITE); alloc_header* h = (alloc_header*)(block - page); int num_pages = (h->size + (page-1)) / page + 2; TORRENT_ASSERT(h->magic == 0x1337); mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE); // fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size)); h->magic = 0; #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #undef PROT_WRITE #endif #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif ::free(block - page); return; #endif // TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS _aligned_free(block); #elif defined TORRENT_BEOS area_id id = area_for(block); if (id < B_OK) return; delete_area(id); #else ::free(block); #endif // TORRENT_WINDOWS } } <commit_msg>fix build with allocator debugging<commit_after>/* Copyright (c) 2009-2013, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/allocator.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #if defined TORRENT_BEOS #include <kernel/OS.h> #include <stdlib.h> // malloc/free #elif !defined TORRENT_WINDOWS #include <stdlib.h> // valloc/free #include <unistd.h> // _SC_PAGESIZE #endif #if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS #include <malloc.h> // memalign and _aligned_malloc #include <stdlib.h> // _aligned_malloc on mingw #endif #ifdef TORRENT_WINDOWS // windows.h must be included after stdlib.h under mingw #include <windows.h> #endif #ifdef TORRENT_MINGW #define _aligned_malloc __mingw_aligned_malloc #define _aligned_free __mingw_aligned_free #endif #ifdef TORRENT_DEBUG_BUFFERS #ifndef TORRENT_WINDOWS #include <sys/mman.h> #endif #include "libtorrent/size_type.hpp" struct alloc_header { libtorrent::size_type size; int magic; char stack[3072]; }; #endif namespace libtorrent { int page_size() { static int s = 0; if (s != 0) return s; #ifdef TORRENT_WINDOWS SYSTEM_INFO si; GetSystemInfo(&si); s = si.dwPageSize; #elif defined TORRENT_BEOS s = B_PAGE_SIZE; #else s = sysconf(_SC_PAGESIZE); #endif // assume the page size is 4 kiB if we // fail to query it if (s <= 0) s = 4096; return s; } char* page_aligned_allocator::malloc(size_type bytes) { TORRENT_ASSERT(bytes >= page_size()); #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); int num_pages = (bytes + (page-1)) / page + 2; char* ret = (char*)valloc(num_pages * page); // make the two surrounding pages non-readable and -writable alloc_header* h = (alloc_header*)ret; h->size = bytes; h->magic = 0x1337; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #endif mprotect(ret, page, PROT_READ); mprotect(ret + (num_pages-1) * page, page, PROT_READ); #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #endif // fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes)); return ret + page; #else #if TORRENT_USE_POSIX_MEMALIGN void* ret; if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0; return (char*)ret; #elif TORRENT_USE_MEMALIGN return (char*)memalign(page_size(), bytes); #elif defined TORRENT_WINDOWS return (char*)_aligned_malloc(bytes, page_size()); #elif defined TORRENT_BEOS void* ret = 0; area_id id = create_area("", &ret, B_ANY_ADDRESS , (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (id < B_OK) return 0; return (char*)ret; #else return (char*)valloc(bytes); #endif #endif // TORRENT_DEBUG_BUFFERS } void page_aligned_allocator::free(char* const block) { #ifdef TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #define PROT_WRITE PAGE_READWRITE #endif int page = page_size(); // make the two surrounding pages non-readable and -writable mprotect(block - page, page, PROT_READ | PROT_WRITE); alloc_header* h = (alloc_header*)(block - page); int num_pages = (h->size + (page-1)) / page + 2; TORRENT_ASSERT(h->magic == 0x1337); mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE); // fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size)); h->magic = 0; #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #undef PROT_WRITE #endif #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif ::free(block - page); return; #endif // TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS _aligned_free(block); #elif defined TORRENT_BEOS area_id id = area_for(block); if (id < B_OK) return; delete_area(id); #else ::free(block); #endif // TORRENT_WINDOWS } } <|endoftext|>
<commit_before>/* Copyright (c) 2009-2013, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/allocator.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #if defined TORRENT_BEOS #include <kernel/OS.h> #include <stdlib.h> // malloc/free #elif !defined TORRENT_WINDOWS #include <stdlib.h> // valloc/free #include <unistd.h> // _SC_PAGESIZE #endif #if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS #include <malloc.h> // memalign and _aligned_malloc #include <stdlib.h> // _aligned_malloc on mingw #endif #ifdef TORRENT_WINDOWS // windows.h must be included after stdlib.h under mingw #include <windows.h> #endif #ifdef TORRENT_MINGW #define _aligned_malloc __mingw_aligned_malloc #define _aligned_free __mingw_aligned_free #endif #ifdef TORRENT_DEBUG_BUFFERS #ifndef TORRENT_WINDOWS #include <sys/mman.h> #endif #include "libtorrent/size_type.hpp" struct alloc_header { libtorrent::size_type size; int magic; char stack[3072]; }; #endif namespace libtorrent { int page_size() { static int s = 0; if (s != 0) return s; #ifdef TORRENT_WINDOWS SYSTEM_INFO si; GetSystemInfo(&si); s = si.dwPageSize; #elif defined TORRENT_BEOS s = B_PAGE_SIZE; #else s = sysconf(_SC_PAGESIZE); #endif // assume the page size is 4 kiB if we // fail to query it if (s <= 0) s = 4096; return s; } char* page_aligned_allocator::malloc(size_type bytes) { TORRENT_ASSERT(bytes >= page_size()); #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); int num_pages = (bytes + (page-1)) / page + 2; char* ret = (char*)valloc(num_pages * page); // make the two surrounding pages non-readable and -writable alloc_header* h = (alloc_header*)ret; h->size = bytes; h->magic = 0x1337; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #endif mprotect(ret, page, PROT_READ); mprotect(ret + (num_pages-1) * page, page, PROT_READ); #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #endif // fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes)); return ret + page; #endif #if TORRENT_USE_POSIX_MEMALIGN void* ret; if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0; return (char*)ret; #elif TORRENT_USE_MEMALIGN return (char*)memalign(page_size(), bytes); #elif defined TORRENT_WINDOWS return (char*)_aligned_malloc(bytes, page_size()); #elif defined TORRENT_BEOS void* ret = 0; area_id id = create_area("", &ret, B_ANY_ADDRESS , (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (id < B_OK) return 0; return (char*)ret; #else return (char*)valloc(bytes); #endif } void page_aligned_allocator::free(char* const block) { #ifdef TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #define PROT_WRITE PAGE_READWRITE #endif int page = page_size(); // make the two surrounding pages non-readable and -writable mprotect(block - page, page, PROT_READ | PROT_WRITE); alloc_header* h = (alloc_header*)(block - page); int num_pages = (h->size + (page-1)) / page + 2; TORRENT_ASSERT(h->magic == 0x1337); mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE); // fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size)); h->magic = 0; #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #undef PROT_WRITE #endif #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif ::free(block - page); return; #endif // TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS _aligned_free(block); #elif defined TORRENT_BEOS area_id id = area_for(block); if (id < B_OK) return; delete_area(id); #else ::free(block); #endif // TORRENT_WINDOWS } } <commit_msg>fix build with allocator debugging<commit_after>/* Copyright (c) 2009-2013, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/allocator.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #if defined TORRENT_BEOS #include <kernel/OS.h> #include <stdlib.h> // malloc/free #elif !defined TORRENT_WINDOWS #include <stdlib.h> // valloc/free #include <unistd.h> // _SC_PAGESIZE #endif #if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS #include <malloc.h> // memalign and _aligned_malloc #include <stdlib.h> // _aligned_malloc on mingw #endif #ifdef TORRENT_WINDOWS // windows.h must be included after stdlib.h under mingw #include <windows.h> #endif #ifdef TORRENT_MINGW #define _aligned_malloc __mingw_aligned_malloc #define _aligned_free __mingw_aligned_free #endif #ifdef TORRENT_DEBUG_BUFFERS #ifndef TORRENT_WINDOWS #include <sys/mman.h> #endif #include "libtorrent/size_type.hpp" struct alloc_header { libtorrent::size_type size; int magic; char stack[3072]; }; #endif namespace libtorrent { int page_size() { static int s = 0; if (s != 0) return s; #ifdef TORRENT_WINDOWS SYSTEM_INFO si; GetSystemInfo(&si); s = si.dwPageSize; #elif defined TORRENT_BEOS s = B_PAGE_SIZE; #else s = sysconf(_SC_PAGESIZE); #endif // assume the page size is 4 kiB if we // fail to query it if (s <= 0) s = 4096; return s; } char* page_aligned_allocator::malloc(size_type bytes) { TORRENT_ASSERT(bytes >= page_size()); #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); int num_pages = (bytes + (page-1)) / page + 2; char* ret = (char*)valloc(num_pages * page); // make the two surrounding pages non-readable and -writable alloc_header* h = (alloc_header*)ret; h->size = bytes; h->magic = 0x1337; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #endif mprotect(ret, page, PROT_READ); mprotect(ret + (num_pages-1) * page, page, PROT_READ); #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #endif // fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes)); return ret + page; #else #if TORRENT_USE_POSIX_MEMALIGN void* ret; if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0; return (char*)ret; #elif TORRENT_USE_MEMALIGN return (char*)memalign(page_size(), bytes); #elif defined TORRENT_WINDOWS return (char*)_aligned_malloc(bytes, page_size()); #elif defined TORRENT_BEOS void* ret = 0; area_id id = create_area("", &ret, B_ANY_ADDRESS , (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (id < B_OK) return 0; return (char*)ret; #else return (char*)valloc(bytes); #endif #endif // TORRENT_DEBUG_BUFFERS } void page_aligned_allocator::free(char* const block) { #ifdef TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #define PROT_WRITE PAGE_READWRITE #endif int page = page_size(); // make the two surrounding pages non-readable and -writable mprotect(block - page, page, PROT_READ | PROT_WRITE); alloc_header* h = (alloc_header*)(block - page); int num_pages = (h->size + (page-1)) / page + 2; TORRENT_ASSERT(h->magic == 0x1337); mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE); // fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size)); h->magic = 0; #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #undef PROT_WRITE #endif #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif ::free(block - page); return; #endif // TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS _aligned_free(block); #elif defined TORRENT_BEOS area_id id = area_for(block); if (id < B_OK) return; delete_area(id); #else ::free(block); #endif // TORRENT_WINDOWS } } <|endoftext|>
<commit_before>/** * * EDFLIB is a cross platform EDF reading writing library in C++ * * by @jonbrennecke - github.com/jonbrennecke * */ // TODO read edf file into hdf5 #include <fstream> #include <map> #include <cstdlib> #include <vector> namespace edf { /** * * basic data structure for containing an EDF * */ struct EDF { // the primary header contains general information about the file std::map<std::string,char*> general_header; // the second header contains information about each signal std::map< std::string, std::vector<char*> > signal_header; // data records is 2-byte short ints std::vector<int16_t*> records; }; /** * * Read an EDF file * * :param filename - file name * :return EDF file struct */ EDF* read ( std::string filename ) { auto edf = new EDF(); // open a binary file stream std::ifstream is(filename, std::ios::in | std::ios::binary); if ( is ) { // constant header sizes and keys const std::vector<int> h1_sizes = { 8,80,80,8,8,8,44,8,8,4 }; const std::vector<int> h2_sizes = { 16,80,8,8,8,8,8,80,8,32 }; const std::vector<std::string> general_keys = { "version", "patient_id", "rec_id", "start_date", "end_time", "header_bytes", "reserved", "num_items", "duration", "num_signals" }; const std::vector<std::string> signal_keys = { "labels", "transducer", "dimension", "phys_min", "phys_max", "dig_min", "dig_max", "prefiltering", "num_samples" }; // read the first 256 bits of header data, containing general // information about the file for( auto iter=h1_sizes.begin(); iter!=h1_sizes.end(); ++iter ) { char *buffer = new char [*iter]; is.read(buffer,*iter); edf->general_header[ general_keys[iter - h1_sizes.begin()] ] = buffer; } // cast num_signals to an int const int ns = atoi( edf->general_header["num_signals"] ); // read the second part of the header for( auto iter=h2_sizes.begin(); iter!=h2_sizes.end(); ++iter ) { // read each signal into a vector std::vector<char*> tmp; for (int i = 0; i < ns; ++i) { char *buffer = new char [*iter]; is.read(buffer,*iter); tmp.push_back( buffer ); } edf->signal_header[ signal_keys[iter - h2_sizes.begin()] ] = tmp; } // the data record begins at 256 + ( num_signals * 256 ) bytes and is stored as n records of 2 * num_samples bytes // values are stored as 2 byte ascii in 2's complement for (int i = 0; i < ns; ++i) { const int samples = atoi( edf->signal_header["num_samples"][i] ); char *buffer = new char[ 2 * samples ]; int16_t *rec = new int16_t[ samples ]; is.read(buffer,i); for (int j = 0; j < samples; j+=2) { rec[j] = buffer[j+1] << 8 | buffer[j]; // little endian rec[j] = ~rec[j] + 1; // two's complement } edf->records.push_back(rec); } is.close(); } return edf; } }<commit_msg>test5<commit_after>/** * * EDFLIB is a cross platform EDF reading writing library in C++ * * by @jonbrennecke - github.com/jonbrennecke * */ // TODO read edf file into hdf5 #include <fstream> #include <map> #include <cstdlib> #include <vector> namespace edf { /** * * basic data structure for containing an EDF * */ struct EDF { // the primary header contains general information about the file std::map<std::string,char*> general_header; // the second header contains information about each signal std::map< std::string, std::vector<char*> > signal_header; // data records is 2-byte short ints std::vector<int16_t*> records; }; /** * * Read an EDF file * * :param filename - file name * :return EDF file struct */ EDF* read ( std::string filename ) { auto edf = new EDF(); // open a binary file stream std::ifstream is(filename, std::ios::in | std::ios::binary); if ( is ) { // constant header sizes and keys const std::vector<int> h1_sizes = { 8,80,80,8,8,8,44,8,8,4 }; const std::vector<int> h2_sizes = { 16,80,8,8,8,8,8,80,8,32 }; const std::vector<std::string> general_keys = { "version", "patient_id", "rec_id", "start_date", "end_time", "header_bytes", "reserved", "num_items", "duration", "num_signals" }; const std::vector<std::string> signal_keys = { "labels", "transducer", "dimension", "phys_min", "phys_max", "dig_min", "dig_max", "prefiltering", "num_samples" }; // read the first 256 bits of header data, containing general // information about the file for( auto iter=h1_sizes.begin(); iter!=h1_sizes.end(); ++iter ) { char *buffer = new char [*iter]; is.read(buffer,*iter); edf->general_header[ general_keys[iter - h1_sizes.begin()] ] = buffer; } // cast num_signals to an int const int ns = atoi( edf->general_header["num_signals"] ); // read the second part of the header for( auto iter=h2_sizes.begin(); iter!=h2_sizes.end(); ++iter ) { // read each signal into a vector std::vector<char*> tmp; for (int i = 0; i < ns; ++i) { char *buffer = new char [*iter]; is.read(buffer,*iter); tmp.push_back( buffer ); } edf->signal_header[ signal_keys[iter - h2_sizes.begin()] ] = tmp; } // the data record begins at 256 + ( num_signals * 256 ) bytes and is stored as n records of 2 * num_samples bytes // values are stored as 2 byte ascii in 2's complement for (int i = 0; i < ns; ++i) { const int samples = atoi( edf->signal_header["num_samples"][i] ); char *buffer = new char[ 2 * samples ]; int16_t *rec = new int16_t[ samples ]; is.read(buffer,i); for (int j = 0; j < samples; j+=2) { rec[j] = buffer[j+1] << 8 | buffer[j]; // little endian rec[j] = ~rec[j] + 1; // two's complement } edf->records.push_back(rec); } is.close(); } return edf; } }<|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/worker_host/message_port_dispatcher.h" #include "base/callback.h" #include "base/singleton.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/renderer_host/resource_message_filter.h" #include "chrome/browser/worker_host/worker_process_host.h" #include "chrome/common/notification_service.h" #include "chrome/common/worker_messages.h" struct MessagePortDispatcher::MessagePort { // sender and route_id are what we need to send messages to the port. IPC::Message::Sender* sender; int route_id; // A function pointer to generate a new route id for the sender above. // Owned by "sender" above, so don't delete. CallbackWithReturnValue<int>::Type* next_routing_id; // A globally unique id for this message port. int message_port_id; // The globally unique id of the entangled message port. int entangled_message_port_id; // If true, all messages to this message port are queued and not delivered. bool queue_messages; QueuedMessages queued_messages; }; MessagePortDispatcher* MessagePortDispatcher::GetInstance() { return Singleton<MessagePortDispatcher>::get(); } MessagePortDispatcher::MessagePortDispatcher() : next_message_port_id_(0), sender_(NULL), next_routing_id_(NULL) { // Receive a notification if a message filter or WorkerProcessHost is deleted. registrar_.Add(this, NotificationType::RESOURCE_MESSAGE_FILTER_SHUTDOWN, NotificationService::AllSources()); registrar_.Add(this, NotificationType::WORKER_PROCESS_HOST_SHUTDOWN, NotificationService::AllSources()); } MessagePortDispatcher::~MessagePortDispatcher() { } bool MessagePortDispatcher::OnMessageReceived( const IPC::Message& message, IPC::Message::Sender* sender, CallbackWithReturnValue<int>::Type* next_routing_id, bool* message_was_ok) { sender_ = sender; next_routing_id_ = next_routing_id; bool handled = true; *message_was_ok = true; IPC_BEGIN_MESSAGE_MAP_EX(MessagePortDispatcher, message, *message_was_ok) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_CreateMessagePort, OnCreate) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_DestroyMessagePort, OnDestroy) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_Entangle, OnEntangle) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_PostMessage, OnPostMessage) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_QueueMessages, OnQueueMessages) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_SendQueuedMessages, OnSendQueuedMessages) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP_EX() sender_ = NULL; next_routing_id_ = NULL; return handled; } void MessagePortDispatcher::UpdateMessagePort( int message_port_id, IPC::Message::Sender* sender, int routing_id, CallbackWithReturnValue<int>::Type* next_routing_id) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } MessagePort& port = message_ports_[message_port_id]; port.sender = sender; port.route_id = routing_id; port.next_routing_id = next_routing_id; } bool MessagePortDispatcher::Send(IPC::Message* message) { return sender_->Send(message); } void MessagePortDispatcher::OnCreate(int *route_id, int* message_port_id) { *message_port_id = ++next_message_port_id_; *route_id = next_routing_id_->Run(); MessagePort port; port.sender = sender_; port.route_id = *route_id; port.next_routing_id = next_routing_id_; port.message_port_id = *message_port_id; port.entangled_message_port_id = MSG_ROUTING_NONE; port.queue_messages = false; message_ports_[*message_port_id] = port; } void MessagePortDispatcher::OnDestroy(int message_port_id) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } DCHECK(message_ports_[message_port_id].queued_messages.empty()); Erase(message_port_id); } void MessagePortDispatcher::OnEntangle(int local_message_port_id, int remote_message_port_id) { if (!message_ports_.count(local_message_port_id) || !message_ports_.count(remote_message_port_id)) { NOTREACHED(); return; } DCHECK(message_ports_[remote_message_port_id].entangled_message_port_id == MSG_ROUTING_NONE); message_ports_[remote_message_port_id].entangled_message_port_id = local_message_port_id; } void MessagePortDispatcher::OnPostMessage( int sender_message_port_id, const string16& message, const std::vector<int>& sent_message_port_ids) { if (!message_ports_.count(sender_message_port_id)) { NOTREACHED(); return; } int entangled_message_port_id = message_ports_[sender_message_port_id].entangled_message_port_id; if (entangled_message_port_id == MSG_ROUTING_NONE) return; // Process could have crashed. if (!message_ports_.count(entangled_message_port_id)) { NOTREACHED(); return; } PostMessageTo(entangled_message_port_id, message, sent_message_port_ids); } void MessagePortDispatcher::PostMessageTo( int message_port_id, const string16& message, const std::vector<int>& sent_message_port_ids) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } for (size_t i = 0; i < sent_message_port_ids.size(); ++i) { if (!message_ports_.count(sent_message_port_ids[i])) { NOTREACHED(); return; } } MessagePort& entangled_port = message_ports_[message_port_id]; std::vector<MessagePort*> sent_ports(sent_message_port_ids.size()); for (size_t i = 0; i < sent_message_port_ids.size(); ++i) { sent_ports[i] = &message_ports_[sent_message_port_ids[i]]; sent_ports[i]->queue_messages = true; } if (entangled_port.queue_messages) { entangled_port.queued_messages.push_back( std::make_pair(message, sent_message_port_ids)); } else { // If a message port was sent around, the new location will need a routing // id. Instead of having the created port send us a sync message to get it, // send along with the message. std::vector<int> new_routing_ids(sent_message_port_ids.size()); for (size_t i = 0; i < sent_message_port_ids.size(); ++i) { new_routing_ids[i] = entangled_port.next_routing_id->Run(); sent_ports[i]->sender = entangled_port.sender; // Update the entry for the sent port as it can be in a different process. sent_ports[i]->route_id = new_routing_ids[i]; } // Now send the message to the entangled port. IPC::Message* ipc_msg = new WorkerProcessMsg_Message( entangled_port.route_id, message, sent_message_port_ids, new_routing_ids); entangled_port.sender->Send(ipc_msg); } } void MessagePortDispatcher::OnQueueMessages(int message_port_id) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } MessagePort& port = message_ports_[message_port_id]; port.sender->Send(new WorkerProcessMsg_MessagesQueued(port.route_id)); port.queue_messages = true; port.sender = NULL; } void MessagePortDispatcher::OnSendQueuedMessages( int message_port_id, const QueuedMessages& queued_messages) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } // Send the queued messages to the port again. This time they'll reach the // new location. MessagePort& port = message_ports_[message_port_id]; port.queue_messages = false; port.queued_messages.insert(port.queued_messages.begin(), queued_messages.begin(), queued_messages.end()); SendQueuedMessagesIfPossible(message_port_id); } void MessagePortDispatcher::SendQueuedMessagesIfPossible(int message_port_id) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } MessagePort& port = message_ports_[message_port_id]; if (port.queue_messages || !port.sender) return; for (QueuedMessages::iterator iter = port.queued_messages.begin(); iter != port.queued_messages.end(); ++iter) { PostMessageTo(message_port_id, iter->first, iter->second); } port.queued_messages.clear(); } void MessagePortDispatcher::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { IPC::Message::Sender* sender = NULL; if (type.value == NotificationType::RESOURCE_MESSAGE_FILTER_SHUTDOWN) { sender = Source<ResourceMessageFilter>(source).ptr(); } else if (type.value == NotificationType::WORKER_PROCESS_HOST_SHUTDOWN) { sender = Source<WorkerProcessHost>(source).ptr(); } else { NOTREACHED(); } // Check if the (possibly) crashed process had any message ports. for (MessagePorts::iterator iter = message_ports_.begin(); iter != message_ports_.end();) { MessagePorts::iterator cur_item = iter++; if (cur_item->second.sender == sender) { Erase(cur_item->first); } } } void MessagePortDispatcher::Erase(int message_port_id) { MessagePorts::iterator erase_item = message_ports_.find(message_port_id); DCHECK(erase_item != message_ports_.end()); int entangled_id = erase_item->second.entangled_message_port_id; if (entangled_id != MSG_ROUTING_NONE) { // Do the disentanglement (and be paranoid about the other side existing // just in case something unusual happened during entanglement). if (message_ports_.count(entangled_id)) { message_ports_[entangled_id].entangled_message_port_id = MSG_ROUTING_NONE; } } message_ports_.erase(erase_item); } <commit_msg>Fix crash in web workers when entangled port sender is null.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/worker_host/message_port_dispatcher.h" #include "base/callback.h" #include "base/singleton.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/renderer_host/resource_message_filter.h" #include "chrome/browser/worker_host/worker_process_host.h" #include "chrome/common/notification_service.h" #include "chrome/common/worker_messages.h" struct MessagePortDispatcher::MessagePort { // sender and route_id are what we need to send messages to the port. IPC::Message::Sender* sender; int route_id; // A function pointer to generate a new route id for the sender above. // Owned by "sender" above, so don't delete. CallbackWithReturnValue<int>::Type* next_routing_id; // A globally unique id for this message port. int message_port_id; // The globally unique id of the entangled message port. int entangled_message_port_id; // If true, all messages to this message port are queued and not delivered. bool queue_messages; QueuedMessages queued_messages; }; MessagePortDispatcher* MessagePortDispatcher::GetInstance() { return Singleton<MessagePortDispatcher>::get(); } MessagePortDispatcher::MessagePortDispatcher() : next_message_port_id_(0), sender_(NULL), next_routing_id_(NULL) { // Receive a notification if a message filter or WorkerProcessHost is deleted. registrar_.Add(this, NotificationType::RESOURCE_MESSAGE_FILTER_SHUTDOWN, NotificationService::AllSources()); registrar_.Add(this, NotificationType::WORKER_PROCESS_HOST_SHUTDOWN, NotificationService::AllSources()); } MessagePortDispatcher::~MessagePortDispatcher() { } bool MessagePortDispatcher::OnMessageReceived( const IPC::Message& message, IPC::Message::Sender* sender, CallbackWithReturnValue<int>::Type* next_routing_id, bool* message_was_ok) { sender_ = sender; next_routing_id_ = next_routing_id; bool handled = true; *message_was_ok = true; IPC_BEGIN_MESSAGE_MAP_EX(MessagePortDispatcher, message, *message_was_ok) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_CreateMessagePort, OnCreate) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_DestroyMessagePort, OnDestroy) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_Entangle, OnEntangle) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_PostMessage, OnPostMessage) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_QueueMessages, OnQueueMessages) IPC_MESSAGE_HANDLER(WorkerProcessHostMsg_SendQueuedMessages, OnSendQueuedMessages) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP_EX() sender_ = NULL; next_routing_id_ = NULL; return handled; } void MessagePortDispatcher::UpdateMessagePort( int message_port_id, IPC::Message::Sender* sender, int routing_id, CallbackWithReturnValue<int>::Type* next_routing_id) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } MessagePort& port = message_ports_[message_port_id]; port.sender = sender; port.route_id = routing_id; port.next_routing_id = next_routing_id; } bool MessagePortDispatcher::Send(IPC::Message* message) { return sender_->Send(message); } void MessagePortDispatcher::OnCreate(int *route_id, int* message_port_id) { *message_port_id = ++next_message_port_id_; *route_id = next_routing_id_->Run(); MessagePort port; port.sender = sender_; port.route_id = *route_id; port.next_routing_id = next_routing_id_; port.message_port_id = *message_port_id; port.entangled_message_port_id = MSG_ROUTING_NONE; port.queue_messages = false; message_ports_[*message_port_id] = port; } void MessagePortDispatcher::OnDestroy(int message_port_id) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } DCHECK(message_ports_[message_port_id].queued_messages.empty()); Erase(message_port_id); } void MessagePortDispatcher::OnEntangle(int local_message_port_id, int remote_message_port_id) { if (!message_ports_.count(local_message_port_id) || !message_ports_.count(remote_message_port_id)) { NOTREACHED(); return; } DCHECK(message_ports_[remote_message_port_id].entangled_message_port_id == MSG_ROUTING_NONE); message_ports_[remote_message_port_id].entangled_message_port_id = local_message_port_id; } void MessagePortDispatcher::OnPostMessage( int sender_message_port_id, const string16& message, const std::vector<int>& sent_message_port_ids) { if (!message_ports_.count(sender_message_port_id)) { NOTREACHED(); return; } int entangled_message_port_id = message_ports_[sender_message_port_id].entangled_message_port_id; if (entangled_message_port_id == MSG_ROUTING_NONE) return; // Process could have crashed. if (!message_ports_.count(entangled_message_port_id)) { NOTREACHED(); return; } PostMessageTo(entangled_message_port_id, message, sent_message_port_ids); } void MessagePortDispatcher::PostMessageTo( int message_port_id, const string16& message, const std::vector<int>& sent_message_port_ids) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } for (size_t i = 0; i < sent_message_port_ids.size(); ++i) { if (!message_ports_.count(sent_message_port_ids[i])) { NOTREACHED(); return; } } MessagePort& entangled_port = message_ports_[message_port_id]; std::vector<MessagePort*> sent_ports(sent_message_port_ids.size()); for (size_t i = 0; i < sent_message_port_ids.size(); ++i) { sent_ports[i] = &message_ports_[sent_message_port_ids[i]]; sent_ports[i]->queue_messages = true; } if (entangled_port.queue_messages) { entangled_port.queued_messages.push_back( std::make_pair(message, sent_message_port_ids)); } else { // If a message port was sent around, the new location will need a routing // id. Instead of having the created port send us a sync message to get it, // send along with the message. std::vector<int> new_routing_ids(sent_message_port_ids.size()); for (size_t i = 0; i < sent_message_port_ids.size(); ++i) { new_routing_ids[i] = entangled_port.next_routing_id->Run(); sent_ports[i]->sender = entangled_port.sender; // Update the entry for the sent port as it can be in a different process. sent_ports[i]->route_id = new_routing_ids[i]; } if (entangled_port.sender) { // Now send the message to the entangled port. IPC::Message* ipc_msg = new WorkerProcessMsg_Message( entangled_port.route_id, message, sent_message_port_ids, new_routing_ids); entangled_port.sender->Send(ipc_msg); } } } void MessagePortDispatcher::OnQueueMessages(int message_port_id) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } MessagePort& port = message_ports_[message_port_id]; if (port.sender) { port.sender->Send(new WorkerProcessMsg_MessagesQueued(port.route_id)); port.queue_messages = true; port.sender = NULL; } } void MessagePortDispatcher::OnSendQueuedMessages( int message_port_id, const QueuedMessages& queued_messages) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } // Send the queued messages to the port again. This time they'll reach the // new location. MessagePort& port = message_ports_[message_port_id]; port.queue_messages = false; port.queued_messages.insert(port.queued_messages.begin(), queued_messages.begin(), queued_messages.end()); SendQueuedMessagesIfPossible(message_port_id); } void MessagePortDispatcher::SendQueuedMessagesIfPossible(int message_port_id) { if (!message_ports_.count(message_port_id)) { NOTREACHED(); return; } MessagePort& port = message_ports_[message_port_id]; if (port.queue_messages || !port.sender) return; for (QueuedMessages::iterator iter = port.queued_messages.begin(); iter != port.queued_messages.end(); ++iter) { PostMessageTo(message_port_id, iter->first, iter->second); } port.queued_messages.clear(); } void MessagePortDispatcher::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { IPC::Message::Sender* sender = NULL; if (type.value == NotificationType::RESOURCE_MESSAGE_FILTER_SHUTDOWN) { sender = Source<ResourceMessageFilter>(source).ptr(); } else if (type.value == NotificationType::WORKER_PROCESS_HOST_SHUTDOWN) { sender = Source<WorkerProcessHost>(source).ptr(); } else { NOTREACHED(); } // Check if the (possibly) crashed process had any message ports. for (MessagePorts::iterator iter = message_ports_.begin(); iter != message_ports_.end();) { MessagePorts::iterator cur_item = iter++; if (cur_item->second.sender == sender) { Erase(cur_item->first); } } } void MessagePortDispatcher::Erase(int message_port_id) { MessagePorts::iterator erase_item = message_ports_.find(message_port_id); DCHECK(erase_item != message_ports_.end()); int entangled_id = erase_item->second.entangled_message_port_id; if (entangled_id != MSG_ROUTING_NONE) { // Do the disentanglement (and be paranoid about the other side existing // just in case something unusual happened during entanglement). if (message_ports_.count(entangled_id)) { message_ports_[entangled_id].entangled_message_port_id = MSG_ROUTING_NONE; } } message_ports_.erase(erase_item); } <|endoftext|>
<commit_before>//g++-5 -Wall --std=c++11 -g -o ds_string_zigzag_conversion ds_string_zigzag_conversion.cc /** * @file String Zigzag traversal * @brief Given string return its zigzag traversal. */ // https://leetcode.com/problems/zigzag-conversion/ #include <iostream> /* std::cout */ #include <algorithm> /* std::max */ #include <string> /* std::string, */ using namespace std; /* * The string "PAYPALISHIRING" is written in a zigzag pattern * on a given number of rows like this: (you may want to display * this pattern in a fixed font for better legibility) * P A H N * A P L S I I G * Y I R * And then read line by line: "PAHNAPLSIIGYIR" * Write the code that will take a string and make this conversion * given a number of rows: * string convert(string text, int nRows); * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". */ /** @brief use a row idx to decide which row should the next * * char be inserted into. For example, given ABCDEFGHIJ, 4 * * A G M * * B F H L N * * C E I K O * * D J P */ string convert(string s, size_t numRows) { int rowadd = 1; /* Corner case: If #rows < 2, this function is a no-op */ if(numRows < 2) return s; /* 2-D vector holding characters one row at a time */ std::vector<std::vector<char>> srows(numRows, std::vector<char>(0)); /* i tracks the input char sequence, i in [0, n) * * row holds row idx to insert the cur char [0, numRows) */ for(size_t i = 0, row = 0; i < s.size(); ++i, row += rowadd) { srows[row].push_back(s[i]); /* Push cur into cur row */ if(row == numRows - 1) rowadd = -1; /* in last row */ else if(row == 0) rowadd = 1; /* in first row */ } string ans; for(auto v : srows) ans += std::string(v.begin(), v.end()); return ans; } struct test_vector { std::string inp; size_t nrows; std::string exp; }; const struct test_vector test[5] = { { "", 5, ""}, { "ABC", 1, "ABC"}, { "PAYPALISHIRING", 3, "PAHNAPLSIIGYIR"}, { "PAYPALISHIRING", 4, "PINALSIGYAHRPI"}, { "1234567890123456789", 5, "1972806837159462453"}, }; int main() { for(auto tst : test) { auto ans = convert(tst.inp, tst.nrows); if(ans != tst.exp) { cout << "Error:convert failed. Exp " << tst.exp << " Got " << ans << " for " << tst.nrows << " rows" << endl; return -1; } } cout << "Info: All manual testcases passed" << endl; return 0; } <commit_msg>Try to fix Travis CI - attempt 2<commit_after>//g++-5 -Wall --std=c++11 -g -o ds_string_zigzag_conversion ds_string_zigzag_conversion.cc /** * @file String Zigzag traversal * @brief Given string return its zigzag traversal. */ // https://leetcode.com/problems/zigzag-conversion/ #include <iostream> /* std::cout */ #include <algorithm> /* std::max */ #include <string> /* std::string */ #include <vector> /* std:vector */ using namespace std; /* * The string "PAYPALISHIRING" is written in a zigzag pattern * on a given number of rows like this: (you may want to display * this pattern in a fixed font for better legibility) * P A H N * A P L S I I G * Y I R * And then read line by line: "PAHNAPLSIIGYIR" * Write the code that will take a string and make this conversion * given a number of rows: * string convert(string text, int nRows); * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". */ /** @brief use a row idx to decide which row should the next * * char be inserted into. For example, given ABCDEFGHIJ, 4 * * A G M * * B F H L N * * C E I K O * * D J P */ string convert(string s, size_t numRows) { int rowadd = 1; /* Corner case: If #rows < 2, this function is a no-op */ if(numRows < 2) return s; /* 2-D vector holding characters one row at a time */ std::vector<std::vector<char>> srows(numRows, std::vector<char>(0)); /* i tracks the input char sequence, i in [0, n) * * row holds row idx to insert the cur char [0, numRows) */ for(size_t i = 0, row = 0; i < s.size(); ++i, row += rowadd) { srows[row].push_back(s[i]); /* Push cur into cur row */ if(row == numRows - 1) rowadd = -1; /* in last row */ else if(row == 0) rowadd = 1; /* in first row */ } string ans; for(auto v : srows) ans += std::string(v.begin(), v.end()); return ans; } struct test_vector { std::string inp; size_t nrows; std::string exp; }; const struct test_vector test[5] = { { "", 5, ""}, { "ABC", 1, "ABC"}, { "PAYPALISHIRING", 3, "PAHNAPLSIIGYIR"}, { "PAYPALISHIRING", 4, "PINALSIGYAHRPI"}, { "1234567890123456789", 5, "1972806837159462453"}, }; int main() { for(auto tst : test) { auto ans = convert(tst.inp, tst.nrows); if(ans != tst.exp) { cout << "Error:convert failed. Exp " << tst.exp << " Got " << ans << " for " << tst.nrows << " rows" << endl; return -1; } } cout << "Info: All manual testcases passed" << endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __ARCH_SPARC_SYSCALLRETURN_HH__ #define __ARCH_SPARC_SYSCALLRETURN_HH__ #include <inttypes.h> #include "arch/sparc/regfile.hh" class SyscallReturn { public: template <class T> SyscallReturn(T v, bool s) { retval = (uint64_t)v; success = s; } template <class T> SyscallReturn(T v) { success = (v >= 0); retval = (uint64_t)v; } ~SyscallReturn() {} SyscallReturn& operator=(const SyscallReturn& s) { retval = s.retval; success = s.success; return *this; } bool successful() { return success; } uint64_t value() { return retval; } private: uint64_t retval; bool success; }; namespace SparcISA { static inline void setSyscallReturn(SyscallReturn return_value, RegFile *regs) { // check for error condition. SPARC syscall convention is to // indicate success/failure in reg the carry bit of the ccr // and put the return value itself in the standard return value reg (). if (return_value.successful()) { // no error, clear XCC.C regs->setMiscReg(MISCREG_CCR, regs->readMiscReg(MISCREG_CCR) & 0xEF); regs->setIntReg(ReturnValueReg, return_value.value()); } else { // got an error, set XCC.C regs->setMiscReg(MISCREG_CCR, regs->readMiscReg(MISCREG_CCR) | 0x10); regs->setIntReg(ReturnValueReg, return_value.value()); } } }; #endif <commit_msg>Set both xcc.c and icc.c on return from a syscall.<commit_after>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __ARCH_SPARC_SYSCALLRETURN_HH__ #define __ARCH_SPARC_SYSCALLRETURN_HH__ #include <inttypes.h> #include "arch/sparc/regfile.hh" class SyscallReturn { public: template <class T> SyscallReturn(T v, bool s) { retval = (uint64_t)v; success = s; } template <class T> SyscallReturn(T v) { success = (v >= 0); retval = (uint64_t)v; } ~SyscallReturn() {} SyscallReturn& operator=(const SyscallReturn& s) { retval = s.retval; success = s.success; return *this; } bool successful() { return success; } uint64_t value() { return retval; } private: uint64_t retval; bool success; }; namespace SparcISA { static inline void setSyscallReturn(SyscallReturn return_value, RegFile *regs) { // check for error condition. SPARC syscall convention is to // indicate success/failure in reg the carry bit of the ccr // and put the return value itself in the standard return value reg (). if (return_value.successful()) { // no error, clear XCC.C regs->setMiscReg(MISCREG_CCR, regs->readMiscReg(MISCREG_CCR) & 0xEE); regs->setIntReg(ReturnValueReg, return_value.value()); } else { // got an error, set XCC.C regs->setMiscReg(MISCREG_CCR, regs->readMiscReg(MISCREG_CCR) | 0x11); regs->setIntReg(ReturnValueReg, return_value.value()); } } }; #endif <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "libmesh/threads.h" // MOOSE includes #include "ComputeMortarNodalAuxBndThread.h" #include "AuxiliarySystem.h" #include "FEProblem.h" #include "MortarNodalAuxKernel.h" template <typename AuxKernelType> ComputeMortarNodalAuxBndThread<AuxKernelType>::ComputeMortarNodalAuxBndThread( FEProblemBase & fe_problem, const MooseObjectWarehouse<AuxKernelType> & storage, const BoundaryID bnd_id, const std::size_t object_container_index) : ThreadedNodeLoop<ConstBndNodeRange, ConstBndNodeRange::const_iterator>(fe_problem), _aux_sys(fe_problem.getAuxiliarySystem()), _storage(storage), _bnd_id(bnd_id), _object_container_index(object_container_index) { } // Splitting Constructor template <typename AuxKernelType> ComputeMortarNodalAuxBndThread<AuxKernelType>::ComputeMortarNodalAuxBndThread( ComputeMortarNodalAuxBndThread & x, Threads::split split) : ThreadedNodeLoop<ConstBndNodeRange, ConstBndNodeRange::const_iterator>(x, split), _aux_sys(x._aux_sys), _storage(x._storage), _bnd_id(x._bnd_id), _object_container_index(x._object_container_index) { } template <typename AuxKernelType> void ComputeMortarNodalAuxBndThread<AuxKernelType>::onNode(ConstBndNodeRange::const_iterator & node_it) { const BndNode * bnode = *node_it; if (bnode->_bnd_id != _bnd_id) return; Node * node = bnode->_node; if (node->processor_id() == _fe_problem.processor_id()) { const auto & kernel = _storage.getActiveBoundaryObjects(_bnd_id, _tid)[_object_container_index]; mooseAssert(dynamic_cast<MortarNodalAuxKernel *>(kernel.get()), "This should be amortar nodal aux kernel"); _fe_problem.reinitNodeFace(node, _bnd_id, _tid); kernel->compute(); // update the solution vector Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); kernel->variable().insert(_aux_sys.solution()); } } template <typename AuxKernelType> void ComputeMortarNodalAuxBndThread<AuxKernelType>::join(const ComputeMortarNodalAuxBndThread & /*y*/) { } template class ComputeMortarNodalAuxBndThread<AuxKernel>; <commit_msg>Only evaluate mortar nodal aux kernel if var is nodal defined<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "libmesh/threads.h" // MOOSE includes #include "ComputeMortarNodalAuxBndThread.h" #include "AuxiliarySystem.h" #include "FEProblem.h" #include "MortarNodalAuxKernel.h" template <typename AuxKernelType> ComputeMortarNodalAuxBndThread<AuxKernelType>::ComputeMortarNodalAuxBndThread( FEProblemBase & fe_problem, const MooseObjectWarehouse<AuxKernelType> & storage, const BoundaryID bnd_id, const std::size_t object_container_index) : ThreadedNodeLoop<ConstBndNodeRange, ConstBndNodeRange::const_iterator>(fe_problem), _aux_sys(fe_problem.getAuxiliarySystem()), _storage(storage), _bnd_id(bnd_id), _object_container_index(object_container_index) { } // Splitting Constructor template <typename AuxKernelType> ComputeMortarNodalAuxBndThread<AuxKernelType>::ComputeMortarNodalAuxBndThread( ComputeMortarNodalAuxBndThread & x, Threads::split split) : ThreadedNodeLoop<ConstBndNodeRange, ConstBndNodeRange::const_iterator>(x, split), _aux_sys(x._aux_sys), _storage(x._storage), _bnd_id(x._bnd_id), _object_container_index(x._object_container_index) { } template <typename AuxKernelType> void ComputeMortarNodalAuxBndThread<AuxKernelType>::onNode(ConstBndNodeRange::const_iterator & node_it) { const BndNode * bnode = *node_it; if (bnode->_bnd_id != _bnd_id) return; Node * node = bnode->_node; if (node->processor_id() == _fe_problem.processor_id()) { const auto & kernel = _storage.getActiveBoundaryObjects(_bnd_id, _tid)[_object_container_index]; mooseAssert(dynamic_cast<MortarNodalAuxKernel *>(kernel.get()), "This should be amortar nodal aux kernel"); _fe_problem.reinitNodeFace(node, _bnd_id, _tid); if (kernel->variable().isNodalDefined()) { kernel->compute(); kernel->variable().insert(_aux_sys.solution()); } } } template <typename AuxKernelType> void ComputeMortarNodalAuxBndThread<AuxKernelType>::join(const ComputeMortarNodalAuxBndThread & /*y*/) { } template class ComputeMortarNodalAuxBndThread<AuxKernel>; <|endoftext|>
<commit_before>#include "rpc/connectivity/multiplexer.hpp" #include "errors.hpp" #include <boost/bind.hpp> #include <boost/function.hpp> #include "rpc/connectivity/connectivity.hpp" message_multiplexer_t::run_t::run_t(message_multiplexer_t *p) : parent(p) { rassert_unreviewed(parent->run == NULL); parent->run = this; for (int i = 0; i < max_tag; i++) { if (parent->clients[i]) { rassert_unreviewed(parent->clients[i]->run); } } } message_multiplexer_t::run_t::~run_t() { rassert_unreviewed(parent->run == this); parent->run = NULL; } void message_multiplexer_t::run_t::on_message(peer_id_t source, read_stream_t *stream) { tag_t tag; archive_result_t res = deserialize(stream, &tag); if (res) { throw fake_archive_exc_t(); } client_t *client = parent->clients[tag]; guarantee_unreviewed(client != NULL, "Got a message for an unfamiliar tag. Apparently " "we aren't compatible with the cluster on the other end."); client->run->message_handler->on_message(source, stream); } message_multiplexer_t::client_t::run_t::run_t(client_t *c, message_handler_t *m) : parent(c), message_handler(m) { rassert_unreviewed(parent->parent->run == NULL); rassert_unreviewed(parent->run == NULL); parent->run = this; } message_multiplexer_t::client_t::run_t::~run_t() { rassert_unreviewed(parent->parent->run == NULL); rassert_unreviewed(parent->run == this); parent->run = NULL; } message_multiplexer_t::client_t::client_t(message_multiplexer_t *p, tag_t t) : parent(p), tag(t), run(NULL) { rassert_unreviewed(parent->run == NULL); rassert_unreviewed(parent->clients[tag] == NULL); parent->clients[tag] = this; } message_multiplexer_t::client_t::~client_t() { rassert_unreviewed(parent->run == NULL); rassert_unreviewed(parent->clients[tag] == this); parent->clients[tag] = NULL; } connectivity_service_t *message_multiplexer_t::client_t::get_connectivity_service() { return parent->message_service->get_connectivity_service(); } class tagged_message_writer_t : public send_message_write_callback_t { public: tagged_message_writer_t(message_multiplexer_t::tag_t _tag, send_message_write_callback_t *_subwriter) : tag(_tag), subwriter(_subwriter) { } virtual ~tagged_message_writer_t() { } void write(write_stream_t *os) { write_message_t msg; msg << tag; int res = send_write_message(os, &msg); if (res) { throw fake_archive_exc_t(); } subwriter->write(os); } private: message_multiplexer_t::tag_t tag; send_message_write_callback_t *subwriter; }; void message_multiplexer_t::client_t::send_message(peer_id_t dest, send_message_write_callback_t *callback) { tagged_message_writer_t writer(tag, callback); parent->message_service->send_message(dest, &writer); } message_multiplexer_t::message_multiplexer_t(message_service_t *super_ms) : message_service(super_ms), run(NULL) { for (int i = 0; i < max_tag; i++) { clients[i] = NULL; } } message_multiplexer_t::~message_multiplexer_t() { rassert_unreviewed(run == NULL); for (int i = 0; i < max_tag; i++) { rassert_unreviewed(clients[i] == NULL); } } <commit_msg>Made assertions reviewed in multiplexer.cc.<commit_after>#include "rpc/connectivity/multiplexer.hpp" #include "errors.hpp" #include <boost/bind.hpp> #include <boost/function.hpp> #include "rpc/connectivity/connectivity.hpp" message_multiplexer_t::run_t::run_t(message_multiplexer_t *p) : parent(p) { guarantee_reviewed(parent->run == NULL); parent->run = this; #ifndef NDEBUG for (int i = 0; i < max_tag; i++) { if (parent->clients[i]) { rassert_reviewed(parent->clients[i]->run); } } #endif // NDEBUG } message_multiplexer_t::run_t::~run_t() { guarantee_reviewed(parent->run == this); parent->run = NULL; } void message_multiplexer_t::run_t::on_message(peer_id_t source, read_stream_t *stream) { tag_t tag; archive_result_t res = deserialize(stream, &tag); if (res) { throw fake_archive_exc_t(); } client_t *client = parent->clients[tag]; guarantee_reviewed(client != NULL, "Got a message for an unfamiliar tag. Apparently " "we aren't compatible with the cluster on the other end."); client->run->message_handler->on_message(source, stream); } message_multiplexer_t::client_t::run_t::run_t(client_t *c, message_handler_t *m) : parent(c), message_handler(m) { guarantee_reviewed(parent->parent->run == NULL); guarantee_reviewed(parent->run == NULL); parent->run = this; } message_multiplexer_t::client_t::run_t::~run_t() { guarantee_reviewed(parent->parent->run == NULL); guarantee_reviewed(parent->run == this); parent->run = NULL; } message_multiplexer_t::client_t::client_t(message_multiplexer_t *p, tag_t t) : parent(p), tag(t), run(NULL) { guarantee_reviewed(parent->run == NULL); guarantee_reviewed(parent->clients[tag] == NULL); parent->clients[tag] = this; } message_multiplexer_t::client_t::~client_t() { guarantee_reviewed(parent->run == NULL); guarantee_reviewed(parent->clients[tag] == this); parent->clients[tag] = NULL; } connectivity_service_t *message_multiplexer_t::client_t::get_connectivity_service() { return parent->message_service->get_connectivity_service(); } class tagged_message_writer_t : public send_message_write_callback_t { public: tagged_message_writer_t(message_multiplexer_t::tag_t _tag, send_message_write_callback_t *_subwriter) : tag(_tag), subwriter(_subwriter) { } virtual ~tagged_message_writer_t() { } void write(write_stream_t *os) { write_message_t msg; msg << tag; int res = send_write_message(os, &msg); if (res) { throw fake_archive_exc_t(); } subwriter->write(os); } private: message_multiplexer_t::tag_t tag; send_message_write_callback_t *subwriter; }; void message_multiplexer_t::client_t::send_message(peer_id_t dest, send_message_write_callback_t *callback) { tagged_message_writer_t writer(tag, callback); parent->message_service->send_message(dest, &writer); } message_multiplexer_t::message_multiplexer_t(message_service_t *super_ms) : message_service(super_ms), run(NULL) { for (int i = 0; i < max_tag; i++) { clients[i] = NULL; } } message_multiplexer_t::~message_multiplexer_t() { guarantee_reviewed(run == NULL); #ifndef NDEBUG for (int i = 0; i < max_tag; i++) { rassert_unreviewed(clients[i] == NULL); } #endif // NDEBUG } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SwUndoPageDesc.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-09-08 14:48:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SW_UNDO_PAGE_DESC_HXX #define _SW_UNDO_PAGE_DESC_HXX #include <undobj.hxx> class SwDoc; class SwPageDesc; class SwUndoPageDesc : public SwUndo { SwPageDescExt aOld, aNew; SwDoc * pDoc; public: SwUndoPageDesc(const SwPageDesc & aOld, const SwPageDesc & aNew, SwDoc * pDoc); virtual ~SwUndoPageDesc(); virtual void Undo(SwUndoIter & rIt); virtual void Redo(SwUndoIter & rIt); virtual void Repeat(SwUndoIter & rIt); virtual SwRewriter GetRewriter() const; }; class SwUndoPageDescCreate : public SwUndo { const SwPageDesc * pDesc; // #116530# SwPageDescExt aNew; SwDoc * pDoc; public: SwUndoPageDescCreate(const SwPageDesc * pNew, SwDoc * pDoc); // #116530# virtual ~SwUndoPageDescCreate(); virtual void Undo(SwUndoIter & rIt); virtual void Redo(SwUndoIter & rIt); virtual void Repeat(SwUndoIter & rIt); virtual SwRewriter GetRewriter() const; }; class SwUndoPageDescDelete : public SwUndo { SwPageDescExt aOld; SwDoc * pDoc; public: SwUndoPageDescDelete(const SwPageDesc & aOld, SwDoc * pDoc); virtual ~SwUndoPageDescDelete(); virtual void Undo(SwUndoIter & rIt); virtual void Redo(SwUndoIter & rIt); virtual void Repeat(SwUndoIter & rIt); virtual SwRewriter GetRewriter() const; }; #endif // _SW_UNDO_PAGE_DESC_CHANGE_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.582); FILE MERGED 2005/09/05 13:35:35 rt 1.3.582.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SwUndoPageDesc.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:30:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SW_UNDO_PAGE_DESC_HXX #define _SW_UNDO_PAGE_DESC_HXX #include <undobj.hxx> class SwDoc; class SwPageDesc; class SwUndoPageDesc : public SwUndo { SwPageDescExt aOld, aNew; SwDoc * pDoc; public: SwUndoPageDesc(const SwPageDesc & aOld, const SwPageDesc & aNew, SwDoc * pDoc); virtual ~SwUndoPageDesc(); virtual void Undo(SwUndoIter & rIt); virtual void Redo(SwUndoIter & rIt); virtual void Repeat(SwUndoIter & rIt); virtual SwRewriter GetRewriter() const; }; class SwUndoPageDescCreate : public SwUndo { const SwPageDesc * pDesc; // #116530# SwPageDescExt aNew; SwDoc * pDoc; public: SwUndoPageDescCreate(const SwPageDesc * pNew, SwDoc * pDoc); // #116530# virtual ~SwUndoPageDescCreate(); virtual void Undo(SwUndoIter & rIt); virtual void Redo(SwUndoIter & rIt); virtual void Repeat(SwUndoIter & rIt); virtual SwRewriter GetRewriter() const; }; class SwUndoPageDescDelete : public SwUndo { SwPageDescExt aOld; SwDoc * pDoc; public: SwUndoPageDescDelete(const SwPageDesc & aOld, SwDoc * pDoc); virtual ~SwUndoPageDescDelete(); virtual void Undo(SwUndoIter & rIt); virtual void Redo(SwUndoIter & rIt); virtual void Repeat(SwUndoIter & rIt); virtual SwRewriter GetRewriter() const; }; #endif // _SW_UNDO_PAGE_DESC_CHANGE_HXX <|endoftext|>
<commit_before>// augmentation_widget.cpp #include "augmentation_widget.hpp" #include <QOpenGLExtraFunctions> #include <QTemporaryFile> #include <QVector2D> #include <QVector3D> #include <math.h> augmentation_widget::augmentation_widget (QWidget* parent) : QOpenGLWidget (parent) , _scale_factor (1.0f) , _x_pos (0.0f) , _y_pos (0.0f) , _vertex_count (0) { } augmentation_widget::~augmentation_widget () { glDeleteBuffers (1, &_object_vbo); glDeleteVertexArrays (1, &_object_vao); } QSize augmentation_widget::minimumSizeHint () const { return QSize (600, 350); } QSize augmentation_widget::sizeHint () const { return QSize (600, 350); } bool augmentation_widget::loadObject (const QString& resource_path) { bool status = false; // extract model from resources into filesystem and parse it QFile resource_file (resource_path); if (resource_file.exists ()) { auto temp_file = QTemporaryFile::createNativeFile (resource_file); QString fs_path = temp_file->fileName (); if (!fs_path.isEmpty ()) { std::vector<float> model_interleaved = _object.load (fs_path.toStdString ()); glBindBuffer (GL_ARRAY_BUFFER, _object_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (float) * model_interleaved.size (), model_interleaved.data (), GL_STATIC_DRAW); glBindBuffer (GL_ARRAY_BUFFER, 0); _vertex_count = model_interleaved.size () / _object.data_per_vertex (); _object.release (); status = true; } } update (); return status; } void augmentation_widget::setBackground (image_t image) { // create background texture glBindTexture (GL_TEXTURE_2D, _texture_background); GLint format_gl; switch (image.format) { case RGB24: { format_gl = GL_RGB; break; } case YUV: case GREY8: case BINARY8: { format_gl = GL_LUMINANCE; break; } } glTexImage2D (GL_TEXTURE_2D, 0, format_gl, image.width, image.height, 0, format_gl, GL_UNSIGNED_BYTE, image.data); // normalize coordinates // TODO: if needed, might be redundant if self written shader already // normalizes texture coords /* glMatrixMode (GL_TEXTURE); glLoadIdentity (); glScalef (1.0 / image.width, 1.0 / image.height, 1); glMatrixMode (GL_MODELVIEW);*/ } void augmentation_widget::setScale (const float scale) { _scale_factor = scale; } void augmentation_widget::setXPosition (const float location) { _x_pos = location; } void augmentation_widget::setYPosition (const float location) { _y_pos = location; } void augmentation_widget::setXRotation (const GLfloat angle) { _x_rot = angle; } void augmentation_widget::setYRotation (const GLfloat angle) { _y_rot = angle; } void augmentation_widget::setZRotation (const GLfloat angle) { _z_rot = angle; } void augmentation_widget::initializeGL () { int status = 0; initializeOpenGLFunctions (); glClearColor (1, 0.5, 1, 1.0f); glEnable (GL_DEPTH_TEST); // glEnable (GL_CULL_FACE); // TODO: add lighting back /* glShadeModel (GL_SMOOTH); glEnable (GL_LIGHTING); glEnable (GL_LIGHT0); glEnable (GL_COLOR_MATERIAL); glMatrixMode (GL_PROJECTION);*/ glEnable (GL_TEXTURE_2D); glGenTextures (1, &_texture_background); glBindTexture (GL_TEXTURE_2D, _texture_background); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // compile and link shaders compile_shaders (); // generate vertex array buffers generate_buffers (); // TODO: add lighting back /*glMatrixMode (GL_MODELVIEW); static GLfloat lightPosition[4] = { 0, 0, 10, 1.0 }; glLightfv (GL_LIGHT0, GL_POSITION, lightPosition); mat_identity (); // gluPerspective (33.7, 1.3, 0.1, 100.0);*/ _mat_projection.ortho (-2.0f, +2.0f, -2.0f, +2.0f, 1.0f, 25.0f); emit initialized (); } void augmentation_widget::generate_buffers () { // setup background vao { glGenVertexArrays (1, &_background_vao); glGenBuffers (1, &_background_vbo); glBindVertexArray (_background_vao); glBindBuffer (GL_ARRAY_BUFFER, _background_vbo); int pos_location = _program_background.attributeLocation ("position"); glVertexAttribPointer (pos_location, 2, GL_FLOAT, GL_FALSE, 4 * sizeof (float), reinterpret_cast<void*> (0)); glEnableVertexAttribArray (pos_location); int tex_location = _program_background.attributeLocation ("tex"); glVertexAttribPointer (tex_location, 2, GL_FLOAT, GL_FALSE, 4 * sizeof (float), reinterpret_cast<void*> (2)); glEnableVertexAttribArray (tex_location); // fill buffer with data GLfloat interleaved_background_buff[6 * 4] = { -1.0, 1.0, // poly 1 a 0.0, 1.0, // poly 1 a tex -1.0, -1.0, // poly 1 b 0.0, 0.0, // poly 1 b tex 1.0, 1.0, // poly 1 c 1.0, 1.0, // poly 1 c tex 1.0, 1.0, // poly 2 a 1.0, 1.0, // poly 2 a tex -1.0, -1.0, // poly 2 b 0.0, 0.0, // poly 2 b tex 1.0, -1.0, // poly 2 c 1.0, 0.0 // poly 2 c tex }; glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 6 * 4, interleaved_background_buff, GL_STATIC_DRAW); // bind texture int tex_uniform = _program_background.uniformLocation ("u_tex_background"); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, _texture_background); glUniform1i (tex_uniform, 0); } // setup object vao { glGenVertexArrays (1, &_object_vao); glGenBuffers (1, &_object_vbo); glBindVertexArray (_object_vao); glBindBuffer (GL_ARRAY_BUFFER, _object_vbo); int pos_location = _program_object.attributeLocation ("position"); glVertexAttribPointer (pos_location, 3, GL_FLOAT, GL_FALSE, 10 * sizeof (float), reinterpret_cast<void*> (0)); glEnableVertexAttribArray (pos_location); int nor_location = _program_object.attributeLocation ("normal"); glVertexAttribPointer (nor_location, 3, GL_FLOAT, GL_FALSE, 10 * sizeof (float), reinterpret_cast<void*> (3)); glEnableVertexAttribArray (nor_location); int col_location = _program_object.attributeLocation ("color"); glVertexAttribPointer (col_location, 4, GL_FLOAT, GL_FALSE, 10 * sizeof (float), reinterpret_cast<void*> (6)); glEnableVertexAttribArray (col_location); glBindBuffer (GL_ARRAY_BUFFER, 0); glBindVertexArray (0); } } void augmentation_widget::compile_shaders () { // background shaders { QFile vs_file (":/GL_shaders/background_vs.glsl"); QFile fs_file (":/GL_shaders/background_fs.glsl"); vs_file.open (QIODevice::ReadOnly); fs_file.open (QIODevice::ReadOnly); QByteArray vs_source = vs_file.readAll (); QByteArray fs_source = fs_file.readAll (); if (QOpenGLContext::currentContext ()->isOpenGLES ()) { vs_source.prepend (QByteArrayLiteral ("#version 300 es\n")); fs_source.prepend (QByteArrayLiteral ("#version 300 es\n")); } else { vs_source.prepend (QByteArrayLiteral ("#version 410\n")); fs_source.prepend (QByteArrayLiteral ("#version 410\n")); } _program_background.addShaderFromSourceCode (QOpenGLShader::Vertex, vs_source); _program_background.addShaderFromSourceCode (QOpenGLShader::Fragment, fs_source); _program_background.link (); } // object shaders { QFile vs_file (":/GL_shaders/basic_vs.glsl"); QFile fs_file (":/GL_shaders/basic_fs.glsl"); vs_file.open (QIODevice::ReadOnly); fs_file.open (QIODevice::ReadOnly); QByteArray vs_source = vs_file.readAll (); QByteArray fs_source = fs_file.readAll (); if (QOpenGLContext::currentContext ()->isOpenGLES ()) { vs_source.prepend (QByteArrayLiteral ("#version 300 es\n")); fs_source.prepend (QByteArrayLiteral ("#version 300 es\n")); } else { vs_source.prepend (QByteArrayLiteral ("#version 410\n")); fs_source.prepend (QByteArrayLiteral ("#version 410\n")); } _program_object.addShaderFromSourceCode (QOpenGLShader::Vertex, vs_source); _program_object.addShaderFromSourceCode (QOpenGLShader::Fragment, fs_source); _program_object.link (); } } void augmentation_widget::resizeGL (int width, int height) { int side = qMin (width, height); glViewport ((width - side) / 2, (height - side) / 2, side, side); _mat_projection.setToIdentity (); // TODO: replace with perspective _mat_projection.ortho (-2.0f, +2.0f, -2.0f, +2.0f, 1.0f, 25.0f); } void augmentation_widget::paintGL () { QMatrix4x4 mat_modelview; // QOpenGLFunctions* f = QOpenGLContext::currentContext // ()->functions // (); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw background _program_background.bind (); draw_background (); // glClear (GL_DEPTH_BUFFER_BIT); mat_modelview.translate (0.0, 0.0, -10.0); _program_object.bind (); // TODO: why is pushing/duplicating the matrix needed? // glPushMatrix (); // draw object // TODO: findout if this is the correct order, should translation not // happen after rotation? mat_modelview.translate (_x_pos, _y_pos, 0); mat_modelview.scale (_scale_factor); mat_modelview.rotate (_x_rot, 1, 0, 0); mat_modelview.rotate (_y_rot, 0, 1, 0); mat_modelview.rotate (_z_rot, 0, 0, 1); mat_modelview = _mat_projection * mat_modelview; _program_object.setUniformValue ("view_matrix", mat_modelview); draw_object (); // TODO: also see todo at glPushMatrix, is pushing and popping needed // here? glPopMatrix (); } void augmentation_widget::draw_object () { // draw the object glBindVertexArray (_object_vao); glDrawArrays (GL_TRIANGLES, 0, _vertex_count); glBindVertexArray (0); } void augmentation_widget::draw_background () { // draw the 2 triangles that form the background glBindVertexArray (_background_vao); glDrawArrays (GL_TRIANGLES, 0, 6); glBindVertexArray (0); } <commit_msg>fix buffer attribute offsets<commit_after>// augmentation_widget.cpp #include "augmentation_widget.hpp" #include <QOpenGLExtraFunctions> #include <QTemporaryFile> #include <QVector2D> #include <QVector3D> #include <math.h> augmentation_widget::augmentation_widget (QWidget* parent) : QOpenGLWidget (parent) , _scale_factor (1.0f) , _x_pos (0.0f) , _y_pos (0.0f) , _vertex_count (0) { } augmentation_widget::~augmentation_widget () { glDeleteBuffers (1, &_object_vbo); glDeleteVertexArrays (1, &_object_vao); } QSize augmentation_widget::minimumSizeHint () const { return QSize (600, 350); } QSize augmentation_widget::sizeHint () const { return QSize (600, 350); } bool augmentation_widget::loadObject (const QString& resource_path) { bool status = false; // extract model from resources into filesystem and parse it QFile resource_file (resource_path); if (resource_file.exists ()) { auto temp_file = QTemporaryFile::createNativeFile (resource_file); QString fs_path = temp_file->fileName (); if (!fs_path.isEmpty ()) { std::vector<float> model_interleaved = _object.load (fs_path.toStdString ()); glBindBuffer (GL_ARRAY_BUFFER, _object_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (float) * model_interleaved.size (), model_interleaved.data (), GL_STATIC_DRAW); glBindBuffer (GL_ARRAY_BUFFER, 0); _vertex_count = model_interleaved.size () / _object.data_per_vertex (); _object.release (); status = true; } } update (); return status; } void augmentation_widget::setBackground (image_t image) { // create background texture glBindTexture (GL_TEXTURE_2D, _texture_background); GLint format_gl; switch (image.format) { case RGB24: { format_gl = GL_RGB; break; } case YUV: case GREY8: case BINARY8: { format_gl = GL_LUMINANCE; break; } } glTexImage2D (GL_TEXTURE_2D, 0, format_gl, image.width, image.height, 0, format_gl, GL_UNSIGNED_BYTE, image.data); // normalize coordinates // TODO: if needed, might be redundant if self written shader already // normalizes texture coords /* glMatrixMode (GL_TEXTURE); glLoadIdentity (); glScalef (1.0 / image.width, 1.0 / image.height, 1); glMatrixMode (GL_MODELVIEW);*/ } void augmentation_widget::setScale (const float scale) { _scale_factor = scale; } void augmentation_widget::setXPosition (const float location) { _x_pos = location; } void augmentation_widget::setYPosition (const float location) { _y_pos = location; } void augmentation_widget::setXRotation (const GLfloat angle) { _x_rot = angle; } void augmentation_widget::setYRotation (const GLfloat angle) { _y_rot = angle; } void augmentation_widget::setZRotation (const GLfloat angle) { _z_rot = angle; } void augmentation_widget::initializeGL () { int status = 0; initializeOpenGLFunctions (); glClearColor (1, 0.5, 1, 1.0f); glEnable (GL_DEPTH_TEST); // glEnable (GL_CULL_FACE); // TODO: add lighting back /* glShadeModel (GL_SMOOTH); glEnable (GL_LIGHTING); glEnable (GL_LIGHT0); glEnable (GL_COLOR_MATERIAL); glMatrixMode (GL_PROJECTION);*/ glEnable (GL_TEXTURE_2D); glGenTextures (1, &_texture_background); glBindTexture (GL_TEXTURE_2D, _texture_background); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // compile and link shaders compile_shaders (); // generate vertex array buffers generate_buffers (); // TODO: add lighting back /*glMatrixMode (GL_MODELVIEW); static GLfloat lightPosition[4] = { 0, 0, 10, 1.0 }; glLightfv (GL_LIGHT0, GL_POSITION, lightPosition); mat_identity (); // gluPerspective (33.7, 1.3, 0.1, 100.0);*/ _mat_projection.ortho (-2.0f, +2.0f, -2.0f, +2.0f, 1.0f, 25.0f); emit initialized (); } void augmentation_widget::generate_buffers () { // setup background vao { glGenVertexArrays (1, &_background_vao); glGenBuffers (1, &_background_vbo); glBindVertexArray (_background_vao); glBindBuffer (GL_ARRAY_BUFFER, _background_vbo); int pos_location = _program_background.attributeLocation ("position"); glVertexAttribPointer (pos_location, 2, GL_FLOAT, GL_FALSE, 4 * sizeof (float), reinterpret_cast<void*> (0)); glEnableVertexAttribArray (pos_location); int tex_location = _program_background.attributeLocation ("tex"); glVertexAttribPointer (tex_location, 2, GL_FLOAT, GL_FALSE, 4 * sizeof (float), reinterpret_cast<void*> (2 * sizeof (float))); glEnableVertexAttribArray (tex_location); // fill buffer with data GLfloat interleaved_background_buff[6 * 4] = { -1.0, 1.0, // poly 1 a 0.0, 1.0, // poly 1 a tex -1.0, -1.0, // poly 1 b 0.0, 0.0, // poly 1 b tex 1.0, 1.0, // poly 1 c 1.0, 1.0, // poly 1 c tex 1.0, 1.0, // poly 2 a 1.0, 1.0, // poly 2 a tex -1.0, -1.0, // poly 2 b 0.0, 0.0, // poly 2 b tex 1.0, -1.0, // poly 2 c 1.0, 0.0 // poly 2 c tex }; glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 6 * 4, interleaved_background_buff, GL_STATIC_DRAW); // bind texture int tex_uniform = _program_background.uniformLocation ("u_tex_background"); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, _texture_background); glUniform1i (tex_uniform, 0); } // setup object vao { glGenVertexArrays (1, &_object_vao); glGenBuffers (1, &_object_vbo); glBindVertexArray (_object_vao); glBindBuffer (GL_ARRAY_BUFFER, _object_vbo); int pos_location = _program_object.attributeLocation ("position"); glVertexAttribPointer (pos_location, 3, GL_FLOAT, GL_FALSE, 10 * sizeof (float), reinterpret_cast<void*> (0)); glEnableVertexAttribArray (pos_location); int nor_location = _program_object.attributeLocation ("normal"); glVertexAttribPointer (nor_location, 3, GL_FLOAT, GL_FALSE, 10 * sizeof (float), reinterpret_cast<void*> (3 * sizeof (float))); glEnableVertexAttribArray (nor_location); int col_location = _program_object.attributeLocation ("color"); glVertexAttribPointer (col_location, 4, GL_FLOAT, GL_FALSE, 10 * sizeof (float), reinterpret_cast<void*> (6 * sizeof (float))); glEnableVertexAttribArray (col_location); glBindBuffer (GL_ARRAY_BUFFER, 0); glBindVertexArray (0); } } void augmentation_widget::compile_shaders () { // background shaders { QFile vs_file (":/GL_shaders/background_vs.glsl"); QFile fs_file (":/GL_shaders/background_fs.glsl"); vs_file.open (QIODevice::ReadOnly); fs_file.open (QIODevice::ReadOnly); QByteArray vs_source = vs_file.readAll (); QByteArray fs_source = fs_file.readAll (); if (QOpenGLContext::currentContext ()->isOpenGLES ()) { vs_source.prepend (QByteArrayLiteral ("#version 300 es\n")); fs_source.prepend (QByteArrayLiteral ("#version 300 es\n")); } else { vs_source.prepend (QByteArrayLiteral ("#version 410\n")); fs_source.prepend (QByteArrayLiteral ("#version 410\n")); } _program_background.addShaderFromSourceCode (QOpenGLShader::Vertex, vs_source); _program_background.addShaderFromSourceCode (QOpenGLShader::Fragment, fs_source); _program_background.link (); } // object shaders { QFile vs_file (":/GL_shaders/basic_vs.glsl"); QFile fs_file (":/GL_shaders/basic_fs.glsl"); vs_file.open (QIODevice::ReadOnly); fs_file.open (QIODevice::ReadOnly); QByteArray vs_source = vs_file.readAll (); QByteArray fs_source = fs_file.readAll (); if (QOpenGLContext::currentContext ()->isOpenGLES ()) { vs_source.prepend (QByteArrayLiteral ("#version 300 es\n")); fs_source.prepend (QByteArrayLiteral ("#version 300 es\n")); } else { vs_source.prepend (QByteArrayLiteral ("#version 410\n")); fs_source.prepend (QByteArrayLiteral ("#version 410\n")); } _program_object.addShaderFromSourceCode (QOpenGLShader::Vertex, vs_source); _program_object.addShaderFromSourceCode (QOpenGLShader::Fragment, fs_source); _program_object.link (); } } void augmentation_widget::resizeGL (int width, int height) { int side = qMin (width, height); glViewport ((width - side) / 2, (height - side) / 2, side, side); _mat_projection.setToIdentity (); // TODO: replace with perspective _mat_projection.ortho (-2.0f, +2.0f, -2.0f, +2.0f, 1.0f, 25.0f); } void augmentation_widget::paintGL () { QMatrix4x4 mat_modelview; // QOpenGLFunctions* f = QOpenGLContext::currentContext // ()->functions // (); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw background _program_background.bind (); draw_background (); // glClear (GL_DEPTH_BUFFER_BIT); mat_modelview.translate (0.0, 0.0, -10.0); _program_object.bind (); // TODO: why is pushing/duplicating the matrix needed? // glPushMatrix (); // draw object // TODO: findout if this is the correct order, should translation not // happen after rotation? mat_modelview.translate (_x_pos, _y_pos, 0); mat_modelview.scale (_scale_factor); mat_modelview.rotate (_x_rot, 1, 0, 0); mat_modelview.rotate (_y_rot, 0, 1, 0); mat_modelview.rotate (_z_rot, 0, 0, 1); mat_modelview = _mat_projection * mat_modelview; _program_object.setUniformValue ("view_matrix", mat_modelview); draw_object (); // TODO: also see todo at glPushMatrix, is pushing and popping needed // here? glPopMatrix (); } void augmentation_widget::draw_object () { // draw the object glBindVertexArray (_object_vao); glDrawArrays (GL_TRIANGLES, 0, _vertex_count); glBindVertexArray (0); } void augmentation_widget::draw_background () { // draw the 2 triangles that form the background glBindVertexArray (_background_vao); glDrawArrays (GL_TRIANGLES, 0, 6); glBindVertexArray (0); } <|endoftext|>
<commit_before>/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements the necessary hooks for mbedTLS. */ #include <assert.h> #include <stdio.h> #include <common/code_utils.hpp> #include <common/encoding.hpp> #include <common/logging.hpp> #include <common/timer.hpp> #include <crypto/sha256.hpp> #include <meshcop/dtls.hpp> #include <thread/thread_netif.hpp> #include <mbedtls/debug.h> namespace Thread { namespace MeshCoP { Dtls::Dtls(ThreadNetif &aNetif): mStarted(false), mTimer(aNetif.GetIp6().mTimerScheduler, &Dtls::HandleTimer, this), mTimerIntermediate(0), mTimerSet(false), mNetif(aNetif) { mProvisioningUrl.Init(); } ThreadError Dtls::Start(bool aClient, ReceiveHandler aReceiveHandler, SendHandler aSendHandler, void *aContext) { static const int ciphersuites[2] = {0xC0FF, 0}; // EC-JPAKE cipher suite int rval; mReceiveHandler = aReceiveHandler; mSendHandler = aSendHandler; mContext = aContext; mClient = aClient; mReceiveMessage = NULL; mbedtls_ssl_init(&mSsl); mbedtls_ssl_config_init(&mConf); mbedtls_ctr_drbg_init(&mCtrDrbg); mbedtls_entropy_init(&mEntropy); mbedtls_debug_set_threshold(4); // XXX: should set personalization data to hardware address rval = mbedtls_ctr_drbg_seed(&mCtrDrbg, mbedtls_entropy_func, &mEntropy, NULL, 0); VerifyOrExit(rval == 0, ;); rval = mbedtls_ssl_config_defaults(&mConf, mClient ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_PRESET_DEFAULT); VerifyOrExit(rval == 0, ;); mbedtls_ssl_conf_rng(&mConf, mbedtls_ctr_drbg_random, &mCtrDrbg); mbedtls_ssl_conf_min_version(&mConf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3); mbedtls_ssl_conf_max_version(&mConf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3); mbedtls_ssl_conf_ciphersuites(&mConf, ciphersuites); mbedtls_ssl_conf_export_keys_cb(&mConf, HandleMbedtlsExportKeys, this); mbedtls_ssl_conf_handshake_timeout(&mConf, 8000, 60000); mbedtls_ssl_conf_dbg(&mConf, HandleMbedtlsDebug, stdout); if (!mClient) { mbedtls_ssl_cookie_init(&mCookieCtx); rval = mbedtls_ssl_cookie_setup(&mCookieCtx, mbedtls_ctr_drbg_random, &mCtrDrbg); VerifyOrExit(rval == 0, ;); mbedtls_ssl_conf_dtls_cookies(&mConf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check, &mCookieCtx); } rval = mbedtls_ssl_setup(&mSsl, &mConf); VerifyOrExit(rval == 0, ;); mbedtls_ssl_set_bio(&mSsl, this, &Dtls::HandleMbedtlsTransmit, HandleMbedtlsReceive, NULL); mbedtls_ssl_set_timer_cb(&mSsl, this, &Dtls::HandleMbedtlsSetTimer, HandleMbedtlsGetTimer); rval = mbedtls_ssl_set_hs_ecjpake_password(&mSsl, mPsk, mPskLength); VerifyOrExit(rval == 0, ;); mStarted = true; Process(); otLogInfoMeshCoP("DTLS started\r\n"); exit: return MapError(rval); } ThreadError Dtls::Stop(void) { mStarted = false; mbedtls_ssl_close_notify(&mSsl); mbedtls_ssl_free(&mSsl); mbedtls_ssl_config_free(&mConf); mbedtls_ctr_drbg_free(&mCtrDrbg); mbedtls_entropy_free(&mEntropy); mbedtls_ssl_cookie_free(&mCookieCtx); return kThreadError_None; } ThreadError Dtls::SetPsk(const uint8_t *aPsk, uint8_t aPskLength) { ThreadError error = kThreadError_None; VerifyOrExit(aPskLength <= sizeof(mPsk), error = kThreadError_InvalidArgs); memcpy(mPsk, aPsk, aPskLength); mPskLength = aPskLength; exit: return error; } ThreadError Dtls::SetClientId(const uint8_t *aClientId, uint8_t aLength) { int rval = mbedtls_ssl_set_client_transport_id(&mSsl, aClientId, aLength); return MapError(rval); } bool Dtls::IsConnected(void) { return mSsl.state == MBEDTLS_SSL_HANDSHAKE_OVER; } ThreadError Dtls::Send(const uint8_t *aBuf, uint16_t aLength) { int rval = mbedtls_ssl_write(&mSsl, aBuf, aLength); return MapError(rval); } ThreadError Dtls::Receive(Message &aMessage, uint16_t aOffset, uint16_t aLength) { mReceiveMessage = &aMessage; mReceiveOffset = aOffset; mReceiveLength = aLength; Process(); return kThreadError_None; } int Dtls::HandleMbedtlsTransmit(void *aContext, const unsigned char *aBuf, size_t aLength) { return static_cast<Dtls *>(aContext)->HandleMbedtlsTransmit(aBuf, aLength); } int Dtls::HandleMbedtlsTransmit(const unsigned char *aBuf, size_t aLength) { ThreadError error; int rval = 0; otLogInfoMeshCoP("Dtls::HandleMbedtlsTransmit\r\n"); error = mSendHandler(mContext, aBuf, (uint16_t)aLength); switch (error) { case kThreadError_None: rval = static_cast<int>(aLength); break; case kThreadError_NoBufs: rval = MBEDTLS_ERR_SSL_WANT_WRITE; break; default: assert(false); break; } return rval; } int Dtls::HandleMbedtlsReceive(void *aContext, unsigned char *aBuf, size_t aLength) { return static_cast<Dtls *>(aContext)->HandleMbedtlsReceive(aBuf, aLength); } int Dtls::HandleMbedtlsReceive(unsigned char *aBuf, size_t aLength) { int rval; otLogInfoMeshCoP("Dtls::HandleMbedtlsReceive\r\n"); VerifyOrExit(mReceiveMessage != NULL && mReceiveLength != 0, rval = MBEDTLS_ERR_SSL_WANT_READ); if (aLength > mReceiveLength) { aLength = mReceiveLength; } rval = (int)mReceiveMessage->Read(mReceiveOffset, (uint16_t)aLength, aBuf); mReceiveOffset += static_cast<uint16_t>(rval); mReceiveLength -= static_cast<uint16_t>(rval); exit: return rval; } int Dtls::HandleMbedtlsGetTimer(void *aContext) { return static_cast<Dtls *>(aContext)->HandleMbedtlsGetTimer(); } int Dtls::HandleMbedtlsGetTimer(void) { int rval; otLogInfoMeshCoP("Dtls::HandleMbedtlsGetTimer\r\n"); if (!mTimerSet) { rval = -1; } else if (!mTimer.IsRunning()) { rval = 2; } else if (static_cast<int32_t>(mTimerIntermediate - Timer::GetNow()) <= 0) { rval = 1; } else { rval = 0; } return rval; } void Dtls::HandleMbedtlsSetTimer(void *aContext, uint32_t aIntermediate, uint32_t aFinish) { static_cast<Dtls *>(aContext)->HandleMbedtlsSetTimer(aIntermediate, aFinish); } void Dtls::HandleMbedtlsSetTimer(uint32_t aIntermediate, uint32_t aFinish) { otLogInfoMeshCoP("Dtls::SetTimer\r\n"); if (aFinish == 0) { mTimerSet = false; mTimer.Stop(); } else { mTimerSet = true; mTimer.Start(aFinish); mTimerIntermediate = Timer::GetNow() + aIntermediate; } } int Dtls::HandleMbedtlsExportKeys(void *aContext, const unsigned char *aMasterSecret, const unsigned char *aKeyBlock, size_t aMacLength, size_t aKeyLength, size_t aIvLength) { return static_cast<Dtls *>(aContext)->HandleMbedtlsExportKeys(aMasterSecret, aKeyBlock, aMacLength, aKeyLength, aIvLength); } int Dtls::HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, const unsigned char *aKeyBlock, size_t aMacLength, size_t aKeyLength, size_t aIvLength) { uint8_t kek[Crypto::Sha256::kHashSize]; Crypto::Sha256 sha256; sha256.Start(); sha256.Update(aKeyBlock, static_cast<uint16_t>(aMacLength + aKeyLength + aIvLength)); sha256.Finish(kek); mNetif.GetKeyManager().SetKek(kek); otLogInfoMeshCoP("Generated KEK\r\n"); (void)aMasterSecret; return 0; } void Dtls::HandleTimer(void *aContext) { static_cast<Dtls *>(aContext)->HandleTimer(); } void Dtls::HandleTimer(void) { Process(); } void Dtls::Process(void) { uint8_t buf[MBEDTLS_SSL_MAX_CONTENT_LEN]; int rval; while (mStarted) { if (mSsl.state != MBEDTLS_SSL_HANDSHAKE_OVER) { rval = mbedtls_ssl_handshake(&mSsl); } else { rval = mbedtls_ssl_read(&mSsl, buf, sizeof(buf)); } if (rval > 0) { mReceiveHandler(mContext, buf, static_cast<uint16_t>(rval)); } else if (rval == 0 || rval == MBEDTLS_ERR_SSL_WANT_READ || rval == MBEDTLS_ERR_SSL_WANT_WRITE) { break; } else { switch (rval) { case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY: mbedtls_ssl_close_notify(&mSsl); break; case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED: case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE: break; default: if (mSsl.state != MBEDTLS_SSL_HANDSHAKE_OVER) { mbedtls_ssl_send_alert_message(&mSsl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE); } break; } mbedtls_ssl_session_reset(&mSsl); mbedtls_ssl_set_hs_ecjpake_password(&mSsl, mPsk, mPskLength); break; } } } ThreadError Dtls::MapError(int rval) { ThreadError error = kThreadError_None; switch (rval) { case MBEDTLS_ERR_SSL_BAD_INPUT_DATA: error = kThreadError_InvalidArgs; break; case MBEDTLS_ERR_SSL_ALLOC_FAILED: error = kThreadError_NoBufs; break; default: assert(rval >= 0); break; } return error; } void Dtls::HandleMbedtlsDebug(void *ctx, int level, const char *file, int line, const char *str) { otLogInfoMeshCoP("%s:%04d: %s\r\n", file, line, str); (void)ctx; (void)level; (void)file; (void)line; (void)str; } } // namespace MeshCoP } // namespace Thread <commit_msg>Send specific DTLS alert for the failure caused by incorrect PSKd (#675)<commit_after>/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements the necessary hooks for mbedTLS. */ #include <assert.h> #include <stdio.h> #include <common/code_utils.hpp> #include <common/encoding.hpp> #include <common/logging.hpp> #include <common/timer.hpp> #include <crypto/sha256.hpp> #include <meshcop/dtls.hpp> #include <thread/thread_netif.hpp> #include <mbedtls/debug.h> namespace Thread { namespace MeshCoP { Dtls::Dtls(ThreadNetif &aNetif): mStarted(false), mTimer(aNetif.GetIp6().mTimerScheduler, &Dtls::HandleTimer, this), mTimerIntermediate(0), mTimerSet(false), mNetif(aNetif) { mProvisioningUrl.Init(); } ThreadError Dtls::Start(bool aClient, ReceiveHandler aReceiveHandler, SendHandler aSendHandler, void *aContext) { static const int ciphersuites[2] = {0xC0FF, 0}; // EC-JPAKE cipher suite int rval; mReceiveHandler = aReceiveHandler; mSendHandler = aSendHandler; mContext = aContext; mClient = aClient; mReceiveMessage = NULL; mbedtls_ssl_init(&mSsl); mbedtls_ssl_config_init(&mConf); mbedtls_ctr_drbg_init(&mCtrDrbg); mbedtls_entropy_init(&mEntropy); mbedtls_debug_set_threshold(4); // XXX: should set personalization data to hardware address rval = mbedtls_ctr_drbg_seed(&mCtrDrbg, mbedtls_entropy_func, &mEntropy, NULL, 0); VerifyOrExit(rval == 0, ;); rval = mbedtls_ssl_config_defaults(&mConf, mClient ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_PRESET_DEFAULT); VerifyOrExit(rval == 0, ;); mbedtls_ssl_conf_rng(&mConf, mbedtls_ctr_drbg_random, &mCtrDrbg); mbedtls_ssl_conf_min_version(&mConf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3); mbedtls_ssl_conf_max_version(&mConf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3); mbedtls_ssl_conf_ciphersuites(&mConf, ciphersuites); mbedtls_ssl_conf_export_keys_cb(&mConf, HandleMbedtlsExportKeys, this); mbedtls_ssl_conf_handshake_timeout(&mConf, 8000, 60000); mbedtls_ssl_conf_dbg(&mConf, HandleMbedtlsDebug, stdout); if (!mClient) { mbedtls_ssl_cookie_init(&mCookieCtx); rval = mbedtls_ssl_cookie_setup(&mCookieCtx, mbedtls_ctr_drbg_random, &mCtrDrbg); VerifyOrExit(rval == 0, ;); mbedtls_ssl_conf_dtls_cookies(&mConf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check, &mCookieCtx); } rval = mbedtls_ssl_setup(&mSsl, &mConf); VerifyOrExit(rval == 0, ;); mbedtls_ssl_set_bio(&mSsl, this, &Dtls::HandleMbedtlsTransmit, HandleMbedtlsReceive, NULL); mbedtls_ssl_set_timer_cb(&mSsl, this, &Dtls::HandleMbedtlsSetTimer, HandleMbedtlsGetTimer); rval = mbedtls_ssl_set_hs_ecjpake_password(&mSsl, mPsk, mPskLength); VerifyOrExit(rval == 0, ;); mStarted = true; Process(); otLogInfoMeshCoP("DTLS started\r\n"); exit: return MapError(rval); } ThreadError Dtls::Stop(void) { mStarted = false; mbedtls_ssl_close_notify(&mSsl); mbedtls_ssl_free(&mSsl); mbedtls_ssl_config_free(&mConf); mbedtls_ctr_drbg_free(&mCtrDrbg); mbedtls_entropy_free(&mEntropy); mbedtls_ssl_cookie_free(&mCookieCtx); return kThreadError_None; } ThreadError Dtls::SetPsk(const uint8_t *aPsk, uint8_t aPskLength) { ThreadError error = kThreadError_None; VerifyOrExit(aPskLength <= sizeof(mPsk), error = kThreadError_InvalidArgs); memcpy(mPsk, aPsk, aPskLength); mPskLength = aPskLength; exit: return error; } ThreadError Dtls::SetClientId(const uint8_t *aClientId, uint8_t aLength) { int rval = mbedtls_ssl_set_client_transport_id(&mSsl, aClientId, aLength); return MapError(rval); } bool Dtls::IsConnected(void) { return mSsl.state == MBEDTLS_SSL_HANDSHAKE_OVER; } ThreadError Dtls::Send(const uint8_t *aBuf, uint16_t aLength) { int rval = mbedtls_ssl_write(&mSsl, aBuf, aLength); return MapError(rval); } ThreadError Dtls::Receive(Message &aMessage, uint16_t aOffset, uint16_t aLength) { mReceiveMessage = &aMessage; mReceiveOffset = aOffset; mReceiveLength = aLength; Process(); return kThreadError_None; } int Dtls::HandleMbedtlsTransmit(void *aContext, const unsigned char *aBuf, size_t aLength) { return static_cast<Dtls *>(aContext)->HandleMbedtlsTransmit(aBuf, aLength); } int Dtls::HandleMbedtlsTransmit(const unsigned char *aBuf, size_t aLength) { ThreadError error; int rval = 0; otLogInfoMeshCoP("Dtls::HandleMbedtlsTransmit\r\n"); error = mSendHandler(mContext, aBuf, (uint16_t)aLength); switch (error) { case kThreadError_None: rval = static_cast<int>(aLength); break; case kThreadError_NoBufs: rval = MBEDTLS_ERR_SSL_WANT_WRITE; break; default: assert(false); break; } return rval; } int Dtls::HandleMbedtlsReceive(void *aContext, unsigned char *aBuf, size_t aLength) { return static_cast<Dtls *>(aContext)->HandleMbedtlsReceive(aBuf, aLength); } int Dtls::HandleMbedtlsReceive(unsigned char *aBuf, size_t aLength) { int rval; otLogInfoMeshCoP("Dtls::HandleMbedtlsReceive\r\n"); VerifyOrExit(mReceiveMessage != NULL && mReceiveLength != 0, rval = MBEDTLS_ERR_SSL_WANT_READ); if (aLength > mReceiveLength) { aLength = mReceiveLength; } rval = (int)mReceiveMessage->Read(mReceiveOffset, (uint16_t)aLength, aBuf); mReceiveOffset += static_cast<uint16_t>(rval); mReceiveLength -= static_cast<uint16_t>(rval); exit: return rval; } int Dtls::HandleMbedtlsGetTimer(void *aContext) { return static_cast<Dtls *>(aContext)->HandleMbedtlsGetTimer(); } int Dtls::HandleMbedtlsGetTimer(void) { int rval; otLogInfoMeshCoP("Dtls::HandleMbedtlsGetTimer\r\n"); if (!mTimerSet) { rval = -1; } else if (!mTimer.IsRunning()) { rval = 2; } else if (static_cast<int32_t>(mTimerIntermediate - Timer::GetNow()) <= 0) { rval = 1; } else { rval = 0; } return rval; } void Dtls::HandleMbedtlsSetTimer(void *aContext, uint32_t aIntermediate, uint32_t aFinish) { static_cast<Dtls *>(aContext)->HandleMbedtlsSetTimer(aIntermediate, aFinish); } void Dtls::HandleMbedtlsSetTimer(uint32_t aIntermediate, uint32_t aFinish) { otLogInfoMeshCoP("Dtls::SetTimer\r\n"); if (aFinish == 0) { mTimerSet = false; mTimer.Stop(); } else { mTimerSet = true; mTimer.Start(aFinish); mTimerIntermediate = Timer::GetNow() + aIntermediate; } } int Dtls::HandleMbedtlsExportKeys(void *aContext, const unsigned char *aMasterSecret, const unsigned char *aKeyBlock, size_t aMacLength, size_t aKeyLength, size_t aIvLength) { return static_cast<Dtls *>(aContext)->HandleMbedtlsExportKeys(aMasterSecret, aKeyBlock, aMacLength, aKeyLength, aIvLength); } int Dtls::HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, const unsigned char *aKeyBlock, size_t aMacLength, size_t aKeyLength, size_t aIvLength) { uint8_t kek[Crypto::Sha256::kHashSize]; Crypto::Sha256 sha256; sha256.Start(); sha256.Update(aKeyBlock, static_cast<uint16_t>(aMacLength + aKeyLength + aIvLength)); sha256.Finish(kek); mNetif.GetKeyManager().SetKek(kek); otLogInfoMeshCoP("Generated KEK\r\n"); (void)aMasterSecret; return 0; } void Dtls::HandleTimer(void *aContext) { static_cast<Dtls *>(aContext)->HandleTimer(); } void Dtls::HandleTimer(void) { Process(); } void Dtls::Process(void) { uint8_t buf[MBEDTLS_SSL_MAX_CONTENT_LEN]; int rval; while (mStarted) { if (mSsl.state != MBEDTLS_SSL_HANDSHAKE_OVER) { rval = mbedtls_ssl_handshake(&mSsl); } else { rval = mbedtls_ssl_read(&mSsl, buf, sizeof(buf)); } if (rval > 0) { mReceiveHandler(mContext, buf, static_cast<uint16_t>(rval)); } else if (rval == 0 || rval == MBEDTLS_ERR_SSL_WANT_READ || rval == MBEDTLS_ERR_SSL_WANT_WRITE) { break; } else { switch (rval) { case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY: mbedtls_ssl_close_notify(&mSsl); break; case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED: case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE: break; case MBEDTLS_ERR_SSL_INVALID_MAC: if (mSsl.state != MBEDTLS_SSL_HANDSHAKE_OVER) { mbedtls_ssl_send_alert_message(&mSsl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC); } break; default: if (mSsl.state != MBEDTLS_SSL_HANDSHAKE_OVER) { mbedtls_ssl_send_alert_message(&mSsl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE); } break; } mbedtls_ssl_session_reset(&mSsl); mbedtls_ssl_set_hs_ecjpake_password(&mSsl, mPsk, mPskLength); break; } } } ThreadError Dtls::MapError(int rval) { ThreadError error = kThreadError_None; switch (rval) { case MBEDTLS_ERR_SSL_BAD_INPUT_DATA: error = kThreadError_InvalidArgs; break; case MBEDTLS_ERR_SSL_ALLOC_FAILED: error = kThreadError_NoBufs; break; default: assert(rval >= 0); break; } return error; } void Dtls::HandleMbedtlsDebug(void *ctx, int level, const char *file, int line, const char *str) { otLogInfoMeshCoP("%s:%04d: %s\r\n", file, line, str); (void)ctx; (void)level; (void)file; (void)line; (void)str; } } // namespace MeshCoP } // namespace Thread <|endoftext|>
<commit_before>/* * ----------------------------------------------------------------------------- * This source file is part of OGRE * (Object-oriented Graphics Rendering Engine) * For the latest info, see http://www.ogre3d.org/ * * Copyright (c) 2000-2013 Torus Knot Software Ltd * * 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. * ----------------------------------------------------------------------------- */ // The algorithm in this file is based heavily on: /* * Progressive Mesh type Polygon Reduction Algorithm * by Stan Melax (c) 1998 */ #include "OgreLodCollapseCostCurvature.h" namespace Ogre { Real LodCollapseCostCurvature::computeEdgeCollapseCost( LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge ) { LodData::Vertex* dst = dstEdge->dst; // Degenerate case check // Are we going to invert a face normal of one of the neighboring faces? // Can occur when we have a very small remaining edge and collapse crosses it // Look for a face normal changing by > 90 degrees if(MESHLOD_QUALITY >= 2) { // 30% speedup if disabled. LodData::VTriangles::iterator it = src->triangles.begin(); LodData::VTriangles::iterator itEnd = src->triangles.end(); for (; it != itEnd; it++) { LodData::Triangle* triangle = *it; // Ignore the deleted faces (those including src & dest) if (!triangle->hasVertex(dst)) { // Test the new face normal LodData::Vertex* pv0, * pv1, * pv2; // Replace src with dest wherever it is pv0 = (triangle->vertex[0] == src) ? dst : triangle->vertex[0]; pv1 = (triangle->vertex[1] == src) ? dst : triangle->vertex[1]; pv2 = (triangle->vertex[2] == src) ? dst : triangle->vertex[2]; // Cross-product 2 edges Vector3 e1 = pv1->position - pv0->position; Vector3 e2 = pv2->position - pv1->position; Vector3 newNormal = e1.crossProduct(e2); // Dot old and new face normal // If < 0 then more than 90 degree difference if (newNormal.dotProduct(triangle->normal) < 0.0f) { // Don't do it! return LodData::NEVER_COLLAPSE_COST; } } } } Real cost; // Special cases // If we're looking at a border vertex if (isBorderVertex(src)) { if (dstEdge->refCount > 1) { // src is on a border, but the src-dest edge has more than one tri on it // So it must be collapsing inwards // Mark as very high-value cost // curvature = 1.0f; cost = 1.0f; } else { // Collapsing ALONG a border // We can't use curvature to measure the effect on the model // Instead, see what effect it has on 'pulling' the other border edges // The more colinear, the less effect it will have // So measure the 'kinkiness' (for want of a better term) // Find the only triangle using this edge. // PMTriangle* triangle = findSideTriangle(src, dst); cost = -1.0f; Vector3 collapseEdge = src->position - dst->position; collapseEdge.normalise(); LodData::VEdges::iterator it = src->edges.begin(); LodData::VEdges::iterator itEnd = src->edges.end(); for (; it != itEnd; it++) { LodData::Vertex* neighbor = it->dst; if (neighbor != dst && it->refCount == 1) { Vector3 otherBorderEdge = src->position - neighbor->position; otherBorderEdge.normalise(); // This time, the nearer the dot is to -1, the better, because that means // the edges are opposite each other, therefore less kinkiness // Scale into [0..1] Real kinkiness = otherBorderEdge.dotProduct(collapseEdge); cost = std::max<Real>(cost, kinkiness); } } cost = (1.002f + cost) * 0.5f; } } else { // not a border // Standard inner vertex // Calculate curvature // use the triangle facing most away from the sides // to determine our curvature term // Iterate over src's faces again cost = 1.0f; LodData::VTriangles::iterator it = src->triangles.begin(); LodData::VTriangles::iterator itEnd = src->triangles.end(); for (; it != itEnd; it++) { Real mincurv = -1.0f; // curve for face i and closer side to it LodData::Triangle* triangle = *it; LodData::VTriangles::iterator it2 = src->triangles.begin(); for (; it2 != itEnd; it2++) { LodData::Triangle* triangle2 = *it2; if (triangle2->hasVertex(dst)) { // Dot product of face normal gives a good delta angle Real dotprod = triangle->normal.dotProduct(triangle2->normal); // NB we do (1-..) to invert curvature where 1 is high curvature [0..1] // Whilst dot product is high when angle difference is low mincurv = std::max<Real>(mincurv, dotprod); } } cost = std::min<Real>(cost, mincurv); } cost = (1.002f - cost) * 0.5f; } // check for texture seam ripping and multiple submeshes if (src->seam) { if (!dst->seam) { cost = std::max<Real>(cost, (Real)0.05f); cost *= 64; } else { if(MESHLOD_QUALITY >= 3) { int seamNeighbors = 0; LodData::Vertex* otherSeam; LodData::VEdges::iterator it = src->edges.begin(); LodData::VEdges::iterator itEnd = src->edges.end(); for (; it != itEnd; it++) { LodData::Vertex* neighbor = it->dst; if(neighbor->seam) { seamNeighbors++; if(neighbor != dst){ otherSeam = neighbor; } } } if(seamNeighbors != 2 || (seamNeighbors == 2 && dst->edges.has(LodData::Edge(otherSeam)))) { cost = std::max<Real>(cost, 0.05f); cost *= 64; } else { cost = std::max<Real>(cost, 0.005f); cost *= 8; } } else { cost = std::max<Real>(cost, 0.005f); cost *= 8; } } } Real diff = src->normal.dotProduct(dst->normal) / 8.0f; Real dist = src->position.distance(dst->position); cost = cost * dist; if(data->mUseVertexNormals){ //Take into account vertex normals. Real normalCost = 0; LodData::VEdges::iterator it = src->edges.begin(); LodData::VEdges::iterator itEnd = src->edges.end(); for (; it != itEnd; it++) { LodData::Vertex* neighbor = it->dst; Real beforeDist = neighbor->position.distance(src->position); Real afterDist = neighbor->position.distance(dst->position); Real beforeDot = neighbor->normal.dotProduct(src->normal); Real afterDot = neighbor->normal.dotProduct(dst->normal); normalCost = std::max<Real>(normalCost, std::max<Real>(diff, std::abs(beforeDot - afterDot)) * std::max<Real>(afterDist/8.0, std::max<Real>(dist, std::abs(beforeDist - afterDist)))); } cost = std::max<Real>(normalCost * 0.25f, cost); } OgreAssert(cost >= 0 && cost != LodData::UNINITIALIZED_COLLAPSE_COST, "Invalid collapse cost"); return cost; } } <commit_msg>Fix compiler warning.<commit_after>/* * ----------------------------------------------------------------------------- * This source file is part of OGRE * (Object-oriented Graphics Rendering Engine) * For the latest info, see http://www.ogre3d.org/ * * Copyright (c) 2000-2013 Torus Knot Software Ltd * * 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. * ----------------------------------------------------------------------------- */ // The algorithm in this file is based heavily on: /* * Progressive Mesh type Polygon Reduction Algorithm * by Stan Melax (c) 1998 */ #include "OgreLodCollapseCostCurvature.h" namespace Ogre { Real LodCollapseCostCurvature::computeEdgeCollapseCost( LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge ) { LodData::Vertex* dst = dstEdge->dst; // Degenerate case check // Are we going to invert a face normal of one of the neighboring faces? // Can occur when we have a very small remaining edge and collapse crosses it // Look for a face normal changing by > 90 degrees if(MESHLOD_QUALITY >= 2) { // 30% speedup if disabled. LodData::VTriangles::iterator it = src->triangles.begin(); LodData::VTriangles::iterator itEnd = src->triangles.end(); for (; it != itEnd; it++) { LodData::Triangle* triangle = *it; // Ignore the deleted faces (those including src & dest) if (!triangle->hasVertex(dst)) { // Test the new face normal LodData::Vertex* pv0, * pv1, * pv2; // Replace src with dest wherever it is pv0 = (triangle->vertex[0] == src) ? dst : triangle->vertex[0]; pv1 = (triangle->vertex[1] == src) ? dst : triangle->vertex[1]; pv2 = (triangle->vertex[2] == src) ? dst : triangle->vertex[2]; // Cross-product 2 edges Vector3 e1 = pv1->position - pv0->position; Vector3 e2 = pv2->position - pv1->position; Vector3 newNormal = e1.crossProduct(e2); // Dot old and new face normal // If < 0 then more than 90 degree difference if (newNormal.dotProduct(triangle->normal) < 0.0f) { // Don't do it! return LodData::NEVER_COLLAPSE_COST; } } } } Real cost; // Special cases // If we're looking at a border vertex if (isBorderVertex(src)) { if (dstEdge->refCount > 1) { // src is on a border, but the src-dest edge has more than one tri on it // So it must be collapsing inwards // Mark as very high-value cost // curvature = 1.0f; cost = 1.0f; } else { // Collapsing ALONG a border // We can't use curvature to measure the effect on the model // Instead, see what effect it has on 'pulling' the other border edges // The more colinear, the less effect it will have // So measure the 'kinkiness' (for want of a better term) // Find the only triangle using this edge. // PMTriangle* triangle = findSideTriangle(src, dst); cost = -1.0f; Vector3 collapseEdge = src->position - dst->position; collapseEdge.normalise(); LodData::VEdges::iterator it = src->edges.begin(); LodData::VEdges::iterator itEnd = src->edges.end(); for (; it != itEnd; it++) { LodData::Vertex* neighbor = it->dst; if (neighbor != dst && it->refCount == 1) { Vector3 otherBorderEdge = src->position - neighbor->position; otherBorderEdge.normalise(); // This time, the nearer the dot is to -1, the better, because that means // the edges are opposite each other, therefore less kinkiness // Scale into [0..1] Real kinkiness = otherBorderEdge.dotProduct(collapseEdge); cost = std::max<Real>(cost, kinkiness); } } cost = (1.002f + cost) * 0.5f; } } else { // not a border // Standard inner vertex // Calculate curvature // use the triangle facing most away from the sides // to determine our curvature term // Iterate over src's faces again cost = 1.0f; LodData::VTriangles::iterator it = src->triangles.begin(); LodData::VTriangles::iterator itEnd = src->triangles.end(); for (; it != itEnd; it++) { Real mincurv = -1.0f; // curve for face i and closer side to it LodData::Triangle* triangle = *it; LodData::VTriangles::iterator it2 = src->triangles.begin(); for (; it2 != itEnd; it2++) { LodData::Triangle* triangle2 = *it2; if (triangle2->hasVertex(dst)) { // Dot product of face normal gives a good delta angle Real dotprod = triangle->normal.dotProduct(triangle2->normal); // NB we do (1-..) to invert curvature where 1 is high curvature [0..1] // Whilst dot product is high when angle difference is low mincurv = std::max<Real>(mincurv, dotprod); } } cost = std::min<Real>(cost, mincurv); } cost = (1.002f - cost) * 0.5f; } // check for texture seam ripping and multiple submeshes if (src->seam) { if (!dst->seam) { cost = std::max<Real>(cost, (Real)0.05f); cost *= 64; } else { if(MESHLOD_QUALITY >= 3) { int seamNeighbors = 0; LodData::Vertex* otherSeam; LodData::VEdges::iterator it = src->edges.begin(); LodData::VEdges::iterator itEnd = src->edges.end(); for (; it != itEnd; it++) { LodData::Vertex* neighbor = it->dst; if(neighbor->seam) { seamNeighbors++; if(neighbor != dst){ otherSeam = neighbor; } } } if(seamNeighbors != 2 || (seamNeighbors == 2 && dst->edges.has(LodData::Edge(otherSeam)))) { cost = std::max<Real>(cost, 0.05f); cost *= 64; } else { cost = std::max<Real>(cost, 0.005f); cost *= 8; } } else { cost = std::max<Real>(cost, 0.005f); cost *= 8; } } } Real diff = src->normal.dotProduct(dst->normal) / 8.0f; Real dist = src->position.distance(dst->position); cost = cost * dist; if(data->mUseVertexNormals){ //Take into account vertex normals. Real normalCost = 0; LodData::VEdges::iterator it = src->edges.begin(); LodData::VEdges::iterator itEnd = src->edges.end(); for (; it != itEnd; it++) { LodData::Vertex* neighbor = it->dst; Real beforeDist = neighbor->position.distance(src->position); Real afterDist = neighbor->position.distance(dst->position); Real beforeDot = neighbor->normal.dotProduct(src->normal); Real afterDot = neighbor->normal.dotProduct(dst->normal); normalCost = std::max<Real>(normalCost, std::max<Real>(diff, std::abs(beforeDot - afterDot)) * std::max<Real>(afterDist/8.0f, std::max<Real>(dist, std::abs(beforeDist - afterDist)))); } cost = std::max<Real>(normalCost * 0.25f, cost); } OgreAssert(cost >= 0 && cost != LodData::UNINITIALIZED_COLLAPSE_COST, "Invalid collapse cost"); return cost; } } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/PointField.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/common/common.h> #include <pcl/PCLPointCloud2.h> #include <pcl/PCLImage.h> #include <pcl/point_cloud.h> #include <pcl/exceptions.h> #include <pcl/console/print.h> #include <pcl/PCLPointField.h> #include <pcl/PCLPointCloud2.h> #include <iostream> #include <ctime> #include <cstdio> #include <cstdlib> using namespace std; using namespace pcl; //catkin_make -DCMAKE_BUILD_TYPE=Release template <typename PointT> void fromPCLPointCloud2ToVelodyneCloud(const pcl::PCLPointCloud2& msg, pcl::PointCloud<PointT>& finalCloud, unsigned int rings) { pcl::PointCloud<PointT>* cloudPerLaser = new pcl::PointCloud<PointT>[rings]; uint8_t* cloud_data[rings]; unsigned int pointsCounter[rings] = {0}; for(unsigned int i=0; i<rings; i++) { cloudPerLaser[i] = pcl::PointCloud<PointT>(); cloudPerLaser[i].header = msg.header; cloudPerLaser[i].width = msg.width; cloudPerLaser[i].height = msg.height; cloudPerLaser[i].is_dense = msg.is_dense == 1; uint32_t num_points = msg.width * msg.height; cloudPerLaser[i].points.resize (num_points); cloud_data[i] = reinterpret_cast<uint8_t*>(&cloudPerLaser[i].points[0]); } for (uint32_t row = 0; row < msg.height; ++row) { const uint8_t* row_data = &msg.data[row * msg.row_step]; for (uint32_t col = 0; col < msg.width; ++col) { const uint8_t* msg_data = row_data + col * msg.point_step; //float* x = (float*)msg_data; //float* y = (float*)(msg_data + 4); //float* z = (float*)(msg_data + 8); //float* i = (float*)(msg_data + 16); uint16_t* ring = (uint16_t*)(msg_data+20); memcpy (cloud_data[*ring], msg_data, 22); pointsCounter[*ring]++; cloud_data[*ring] += sizeof (PointT); } } unsigned int maxLength = 0; for(unsigned int i=0; i<rings; i++) { cloudPerLaser[i].width = pointsCounter[i]; cloudPerLaser[i].height = 1; cloudPerLaser[i].points.resize (pointsCounter[i]); if(pointsCounter[i]>maxLength) maxLength = pointsCounter[i]; } finalCloud.header = msg.header; finalCloud.width = maxLength; finalCloud.height = rings; finalCloud.is_dense = msg.is_dense == 1; finalCloud.points.resize (maxLength*rings); for (size_t row = 0; row < rings; ++row) for (size_t col = 0; col < maxLength; ++col) finalCloud(col, row) = cloudPerLaser[row].points[col%(cloudPerLaser[row].points.size())]; } void cloud_callback (const sensor_msgs::PointCloud2ConstPtr& cloud_msg) { /*cout<<"Field: "<<cloud_msg->fields[0].name<<endl; cout<<"-------"<<cloud_msg->fields[0].offset<<endl; cout<<"-------"<<cloud_msg->fields[0].datatype<<endl; cout<<"-------"<<cloud_msg->fields[0].count<<endl; cout<<"Field: "<<cloud_msg->fields[1].name<<endl; cout<<"-------"<<cloud_msg->fields[1].offset<<endl; cout<<"-------"<<cloud_msg->fields[1].datatype<<endl; cout<<"-------"<<cloud_msg->fields[1].count<<endl; cout<<"Field: "<<cloud_msg->fields[2].name<<endl; cout<<"-------"<<cloud_msg->fields[2].offset<<endl; cout<<"-------"<<cloud_msg->fields[2].datatype<<endl; cout<<"-------"<<cloud_msg->fields[2].count<<endl; cout<<"Field: "<<cloud_msg->fields[3].name<<endl; cout<<"-------"<<cloud_msg->fields[3].offset<<endl; cout<<"-------"<<cloud_msg->fields[3].datatype<<endl; cout<<"-------"<<cloud_msg->fields[3].count<<endl; cout<<"Field: "<<cloud_msg->fields[4].name<<endl; cout<<"-------"<<cloud_msg->fields[4].offset<<endl; cout<<"-------"<<cloud_msg->fields[4].datatype<<endl; cout<<"-------"<<cloud_msg->fields[4].count<<endl;*/ pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>); pcl::PCLPointCloud2 pcl_pc2; pcl_conversions::toPCL(*cloud_msg, pcl_pc2); fromPCLPointCloud2ToVelodyneCloud (pcl_pc2, *cloud, 16); pcl::PCDWriter writer; writer.write<pcl::PointXYZI> ("cloud.pcd", *cloud, false); } int main (int argc, char** argv) { ros::init (argc, argv, "vlp16_cloud"); ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe<sensor_msgs::PointCloud2> ("/velodyne_points", 10, cloud_callback); ros::spin (); }<commit_msg>Commit 2<commit_after>#include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/PointField.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/common/common.h> #include <pcl/PCLPointCloud2.h> #include <pcl/PCLImage.h> #include <pcl/point_cloud.h> #include <pcl/exceptions.h> #include <pcl/console/print.h> #include <pcl/PCLPointField.h> #include <pcl/PCLPointCloud2.h> #include <iostream> #include <ctime> #include <cstdio> #include <cstdlib> using namespace std; using namespace pcl; //catkin_make -DCMAKE_BUILD_TYPE=Release template <typename PointT> void fromPCLPointCloud2ToVelodyneCloud(const pcl::PCLPointCloud2& msg, pcl::PointCloud<PointT>& cloud1D, pcl::PointCloud<PointT>& cloud2D, unsigned int rings) { cloud1D.header = msg.header; cloud1D.width = msg.width; cloud1D.height = msg.height; cloud1D.is_dense = msg.is_dense == 1; uint32_t num_points = msg.width * msg.height; cloud1D.points.resize (num_points); uint8_t* cloud_data1 = reinterpret_cast<uint8_t*>(&cloud1D.points[0]); pcl::PointCloud<PointT>* cloudPerLaser = new pcl::PointCloud<PointT>[rings]; uint8_t* cloud_data2[rings]; unsigned int pointsCounter[rings] = {0}; for(unsigned int i=0; i<rings; ++i) { cloudPerLaser[i] = pcl::PointCloud<PointT>(); cloudPerLaser[i].header = msg.header; cloudPerLaser[i].width = msg.width; cloudPerLaser[i].height = msg.height; cloudPerLaser[i].is_dense = msg.is_dense == 1; cloudPerLaser[i].points.resize (num_points); cloud_data2[i] = reinterpret_cast<uint8_t*>(&cloudPerLaser[i].points[0]); } for (uint32_t row = 0; row < msg.height; ++row) { const uint8_t* row_data = &msg.data[row * msg.row_step]; for (uint32_t col = 0; col < msg.width; ++col) { const uint8_t* msg_data = row_data + col * msg.point_step; //float* x = (float*)msg_data; //float* y = (float*)(msg_data + 4); //float* z = (float*)(msg_data + 8); //float* i = (float*)(msg_data + 16); uint16_t* ring = (uint16_t*)(msg_data+20); memcpy (cloud_data2[*ring], msg_data, 22); memcpy (cloud_data1, msg_data, 22); pointsCounter[*ring]++; cloud_data1 += sizeof (PointT); cloud_data2[*ring] += sizeof (PointT); } } unsigned int maxLength = 0; for(unsigned int i=0; i<rings; ++i) { cloudPerLaser[i].width = pointsCounter[i]; cloudPerLaser[i].height = 1; cloudPerLaser[i].points.resize (pointsCounter[i]); if(pointsCounter[i]>maxLength) maxLength = pointsCounter[i]; } cloud2D.header = msg.header; cloud2D.width = maxLength; cloud2D.height = rings; cloud2D.is_dense = msg.is_dense == 1; cloud2D.points.resize (maxLength*rings); for (size_t row = 0; row < rings; ++row) for (size_t col = 0; col < maxLength; ++col) cloud2D(col, row) = cloudPerLaser[row].points[col%(cloudPerLaser[row].points.size())]; } void cloud_callback (const sensor_msgs::PointCloud2ConstPtr& cloud_msg) { /*cout<<"Field: "<<cloud_msg->fields[0].name<<endl; cout<<"-------"<<cloud_msg->fields[0].offset<<endl; cout<<"-------"<<cloud_msg->fields[0].datatype<<endl; cout<<"-------"<<cloud_msg->fields[0].count<<endl; cout<<"Field: "<<cloud_msg->fields[1].name<<endl; cout<<"-------"<<cloud_msg->fields[1].offset<<endl; cout<<"-------"<<cloud_msg->fields[1].datatype<<endl; cout<<"-------"<<cloud_msg->fields[1].count<<endl; cout<<"Field: "<<cloud_msg->fields[2].name<<endl; cout<<"-------"<<cloud_msg->fields[2].offset<<endl; cout<<"-------"<<cloud_msg->fields[2].datatype<<endl; cout<<"-------"<<cloud_msg->fields[2].count<<endl; cout<<"Field: "<<cloud_msg->fields[3].name<<endl; cout<<"-------"<<cloud_msg->fields[3].offset<<endl; cout<<"-------"<<cloud_msg->fields[3].datatype<<endl; cout<<"-------"<<cloud_msg->fields[3].count<<endl; cout<<"Field: "<<cloud_msg->fields[4].name<<endl; cout<<"-------"<<cloud_msg->fields[4].offset<<endl; cout<<"-------"<<cloud_msg->fields[4].datatype<<endl; cout<<"-------"<<cloud_msg->fields[4].count<<endl;*/ pcl::PointCloud<pcl::PointXYZI>::Ptr cloud1D(new pcl::PointCloud<pcl::PointXYZI>); pcl::PointCloud<pcl::PointXYZI>::Ptr cloud2D(new pcl::PointCloud<pcl::PointXYZI>); pcl::PCLPointCloud2 pcl_pc2; pcl_conversions::toPCL(*cloud_msg, pcl_pc2); fromPCLPointCloud2ToVelodyneCloud (pcl_pc2, *cloud1D, *cloud2D, 16); pcl::PCDWriter writer; writer.write<pcl::PointXYZI> ("cloud1D.pcd", *cloud1D, false); writer.write<pcl::PointXYZI> ("cloud2D.pcd", *cloud2D, false); } int main (int argc, char** argv) { ros::init (argc, argv, "vlp16_cloud"); ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe<sensor_msgs::PointCloud2> ("/velodyne_points", 10, cloud_callback); ros::spin (); }<|endoftext|>