//使用頻度が高いオブジェクト関係はこちらで保持 //保存する際はキーを確認し、重複してなければ保持する void App::RegisterResource(const wstring& Key, const shared_ptr<BaseResource>& ResObj) { try { if (Key == L"") { throw BaseException( L"キーが空白です", L"if(Key == L\"\")", L"App::RegisterResource()" ); } if (!ResObj) { throw BaseException( L"リソースが不定です", L"if(!pResObj)", L"App::RegisterResource()" ); } map<wstring, shared_ptr<BaseResource> >::iterator it; //重複ポインタの検査 for (it = m_ResMap.begin(); it != m_ResMap.end(); it++) { if (it->second == ResObj) { //ポインタが重複していても、キーが同じなら //すでに登録されているのでリターン if (it->first == Key) { return; } wstring keyerr = Key; throw BaseException( L"すでにそのリソースは登録されています", keyerr, L"App::RegisterResource()" ); } } //重複キーの検査 it = m_ResMap.find(Key); if (it != m_ResMap.end()) { //指定の名前が見つかった //例外発生 wstring keyerr = Key; throw BaseException( L"すでにそのキーは登録されています", keyerr, L"App::RegisterResource()" ); } else { //見つからない //リソースペアの追加 m_ResMap[Key] = ResObj; } } catch (...) { throw; } }
ID3D11BlendState* RenderState::GetAlphaBlendEx()const{ if (!pImpl->m_AlphaBlendExPtr){ auto Dev = App::GetApp()->GetDeviceResources(); auto pDx11Device = Dev->GetD3DDevice(); D3D11_BLEND_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.RenderTarget[0].BlendEnable = true; desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; // desc.RenderTarget[0].DestBlend = D3D11_BLEND_DEST_ALPHA; desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; HRESULT hr = pDx11Device->CreateBlendState(&desc, &pImpl->m_AlphaBlendExPtr); if (FAILED(hr)){ // 初期化失敗 throw BaseException( L"ブレンドステート作成に失敗しました。", L"if(FAILED(pDx11Device->CreateBlendState()))", L"BasicState::GetAlphaBlendEx()" ); } } return pImpl->m_AlphaBlendExPtr.Get(); }
//レンダリングターゲットを開始する void DefaultRenderTarget::StartRenderTarget(){ auto Dev = App::GetApp()->GetDeviceResources(); auto pD3D11Device = Dev->GetD3DDevice(); auto pD3D11DeviceContext = Dev->GetD3DDeviceContext(); ID3D11RenderTargetView* pV = pImpl->m_D3D11RenderTargetView.Get(); //レンダリングターゲットとステンシルを設定 pD3D11DeviceContext->OMSetRenderTargets(1, &pV, pImpl->m_DepthStencilView.Get()); //ビューポートの設定 if (pImpl->m_Stage.expired()){ throw BaseException( L"ステージが無効です", L"if (pImpl->m_Stage.expired())", L"DefaultRenderTarget::StartRenderTarget()" ); } auto StagePtr = pImpl->m_Stage.lock(); pD3D11DeviceContext->RSSetViewports(1, StagePtr->GetTargetViewPortRealPtr()); //シェーダーリソースビューのクリア ID3D11ShaderResourceView* pNull[1] = { nullptr }; pD3D11DeviceContext->PSSetShaderResources(0, _countof(pNull), pNull); pD3D11DeviceContext->PSSetShaderResources(1, _countof(pNull), pNull); //シェーダーは指定しない pD3D11DeviceContext->VSSetShader(nullptr, nullptr, 0); pD3D11DeviceContext->PSSetShader(nullptr, nullptr, 0); pD3D11DeviceContext->GSSetShader(nullptr, nullptr, 0); //ブレンドは指定しない pD3D11DeviceContext->OMSetBlendState(nullptr, nullptr, 0xffffffff); }
//-------------------------------------------------------------------------------------- // void RenderState::Impl::CreateRasterizerState( // D3D11_CULL_MODE cullMode, //カリング // D3D11_FILL_MODE fillMode, //塗り // ID3D11RasterizerState** pResult, //受け取るインターフェイス // bool Scissor = false //画面分割するかどうか // ); // 用途: ラスタライザステートを作成するヘルパー関数 // 戻り値: なし //-------------------------------------------------------------------------------------- void RenderState::Impl::CreateRasterizerState(D3D11_CULL_MODE cullMode, D3D11_FILL_MODE fillMode, ID3D11RasterizerState** pResult, bool Scissor){ try{ auto Dev = App::GetApp()->GetDeviceResources(); auto pDx11Device = Dev->GetD3DDevice(); D3D11_RASTERIZER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.CullMode = cullMode; desc.FillMode = fillMode; desc.DepthClipEnable = true; desc.MultisampleEnable = true; desc.ScissorEnable = Scissor; HRESULT hr = pDx11Device->CreateRasterizerState(&desc, pResult); if (FAILED(hr)){ // 初期化失敗 throw BaseException( L"ラスタライザステート作成に失敗しました。", L"if(FAILED(pDx11Device->CreateRasterizerState()))", L"RenderState::Impl::CreateRasterizerState()" ); } } catch (...){ throw; } }
void App::UpdateDraw(unsigned int SyncInterval) { if (!m_WorldInterface) { //シーンがが無効なら throw BaseException( L"シーンがありません", L"if(!m_SceneInterface)", L"App::UpdateDraw()" ); } // シーン オブジェクトを更新します。 m_InputDevice.ResetControlerState(); m_Timer.Tick([&]() { m_WorldInterface->OnUpdate(); }); // 初回更新前にレンダリングは行わない。 if (GetFrameCount() == 0) { return; } m_WorldInterface->OnDraw(); // バックバッファからフロントバッファに転送 m_DeviceResources->Present(SyncInterval, 0); }
//-------------------------------------------------------------------------------------- // void RenderState::Impl::CreateBlendState( // D3D11_BLEND srcBlend, //ソースブレンド // D3D11_BLEND destBlend, //デストブレンド // ID3D11BlendState** pResult //受け取るインターフェイス // ); // 用途: ブレンドステートを作成するヘルパー関数 // 戻り値: なし //-------------------------------------------------------------------------------------- void RenderState::Impl::CreateBlendState(D3D11_BLEND srcBlend, D3D11_BLEND destBlend, ID3D11BlendState** pResult){ try{ auto Dev = App::GetApp()->GetDeviceResources(); auto pDx11Device = Dev->GetD3DDevice(); D3D11_BLEND_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.RenderTarget[0].BlendEnable = (srcBlend != D3D11_BLEND_ONE) || (destBlend != D3D11_BLEND_ZERO); desc.RenderTarget[0].SrcBlend = desc.RenderTarget[0].SrcBlendAlpha = srcBlend; desc.RenderTarget[0].DestBlend = desc.RenderTarget[0].DestBlendAlpha = destBlend; desc.RenderTarget[0].BlendOp = desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; HRESULT hr = pDx11Device->CreateBlendState(&desc, pResult); if (FAILED(hr)){ // 初期化失敗 throw BaseException( L"ブレンドステート作成に失敗しました。", L"if(FAILED(pDx11Device->CreateBlendState()))", L"RenderState::Impl::CreateBlendState()" ); } } catch (...){ throw; } }
void SpriteBase::OnUpdate() { float ElapsedTime = App::GetApp()->GetElapsedTime(); auto Dev = App::GetApp()->GetDeviceResources(); auto pD3D11DeviceContext = Dev->GetD3DDeviceContext(); //頂点の変更 //D3D11_MAP_WRITE_DISCARDは重要。この処理により、GPUに邪魔されない D3D11_MAP mapType = D3D11_MAP_WRITE_DISCARD; D3D11_MAPPED_SUBRESOURCE mappedBuffer; //頂点のマップ if (FAILED(pD3D11DeviceContext->Map(m_SquareMesh->GetVertexBuffer().Get(), 0, mapType, 0, &mappedBuffer))) { // Map失敗 throw BaseException( L"頂点のMapに失敗しました。", L"if(FAILED(pID3D11DeviceContext->Map()))", L"WrappedSprite::UpdateVertex()" ); } //頂点の変更 VertexPositionColorTexture* vertices = (VertexPositionColorTexture*)mappedBuffer.pData; //仮想関数呼び出し UpdateVertex(ElapsedTime, vertices); //アンマップ pD3D11DeviceContext->Unmap(m_SquareMesh->GetVertexBuffer().Get(), 0); }
// static void Dialog::ReadLimitInt(std::istream &is, std::ostream &os, int *val, int lo, int hi, std::string prompt) { int ret; char extra; std::string line; while (1) { os << prompt << " [" << lo << ", " << hi << "]: "; do { getline(is, line); if (is.eof()) throw BaseException("Unexpected EOF"); } while (line.empty()); ret = sscanf(line.c_str(), " %d %c ", val, &extra); if (ret == 0) { os << "Badly formatted input" << std::endl; continue; } else if (ret == 2) { os << "Unexpected garbage after value." << std::endl; continue; } if (InRange<int>(lo, *val, hi + 1)) break; os << "Please enter a value between " << lo << " and " << hi << std::endl; } }
// cause_error(type_of_error) int ModApiServer::l_cause_error(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string type_of_error = "none"; if(lua_isstring(L, 1)) type_of_error = lua_tostring(L, 1); errorstream << "Error handler test called, errortype=" << type_of_error << std::endl; if(type_of_error == "segv") { volatile int* some_pointer = 0; errorstream << "Cause a sigsegv now: " << (*some_pointer) << std::endl; } else if (type_of_error == "zerodivision") { unsigned int some_number = porting::getTimeS(); unsigned int zerovalue = 0; unsigned int result = some_number / zerovalue; errorstream << "Well this shouldn't ever be shown: " << result << std::endl; } else if (type_of_error == "exception") { throw BaseException("Errorhandler test fct called"); } return 0; }
void Database_SQLite3::createDirs(std::string path) { if(fs::CreateAllDirs(path) == false) { infostream<<DTIME<<"Database_SQLite3: Failed to create directory " <<"\""<<path<<"\""<<std::endl; throw BaseException("Database_SQLite3 failed to create directory"); } }
Theron::ActorRef CreateActor(const std::string& id) { typename IdToActorMap::iterator i = associations_.find(id); if (i != associations_.end()) { return (*(i->second))(); } throw BaseException(UnKnownPro, "Unknown product" ); }
//追いかけるオブジェクトの作成 void GameStage::CreateSeekObject(){ //オブジェクトのグループを作成する auto Group = CreateSharedObjectGroup(L"ObjectGroup"); wstring MediaPath = App::GetApp()->m_wstrRelativeDataPath; //XMLファイルの決定 wstring XMLFilename = MediaPath + L"GameStage.xml"; //ローカル上にXMLファイル読み取りクラスを作成 XmlDocReader GameStageXml(XMLFilename); //メンバ関数でゲームオブジェクトのノードを取得 auto ObjectsRoot = GameStageXml.GetSelectSingleNode(L"GameStage/GameObjects"); if (!ObjectsRoot){ throw BaseException( L"GameStage/GameObjectsが見つかりません", L"if (!ObjectsRoot)", L"GameStage::CreateSeekObject()" ); } //static関数呼び出しで、SeekObjectノードの配列を得る auto SeekObjects = XmlDocReader::GetSelectNodes(ObjectsRoot, L"SeekObject"); //static関数呼び出しで、SeekObjectノードの数を得る long lCountNode = XmlDocReader::GetLength(SeekObjects); for (long i = 0; i < lCountNode; i++){ //static関数呼び出しで、個別のノードを得る auto PositionNode = XmlDocReader::GetItem(SeekObjects, i); //static関数呼び出しで、位置ノードを得る auto StartPosNode = XmlDocReader::GetSelectSingleNode(PositionNode, L"StartPosition"); //static関数呼び出しで、ノード内の文字列を得る wstring StartPosStr = XmlDocReader::GetText(StartPosNode); if (StartPosStr == L""){ throw BaseException( L"スタート位置が空白です", L"if (StartPosStr == L\"\")", L"GameStage::CreateSeekObject()" ); } vector< wstring > StrVec; Util::WStrToTokenVector(StrVec, StartPosStr, L','); //分解した配列からデータを取り出す AddGameObject<SeekObject>(Vector3(StrVec[0], StrVec[1], StrVec[2])); } }
Janitor::~Janitor() { // expect the item to be deleted to be first on list // but must be prepared to search list if (OnStack) { #ifdef CLEAN_LIST cout << "Delete from clean-list " << (unsigned long)this << "\n"; #endif Janitor* lastjan = JumpBase::jl->janitor; if (this == lastjan) JumpBase::jl->janitor = NextJanitor; else { for (Janitor* jan = lastjan->NextJanitor; jan; jan = lastjan->NextJanitor) { if (jan==this) { lastjan->NextJanitor = jan->NextJanitor; return; } lastjan=jan; } Throw(BaseException( "Cannot resolve memory linked list\nSee notes in myexcept.cpp for details\n" )); // This message occurs when a call to ~Janitor() occurs, apparently // without a corresponding call to Janitor(). This could happen if my // way of deciding whether a constructor is being called by new // fails. // It may happen if you are using my simulated exceptions and also have // your compiler s exceptions turned on. // It can also happen if you have a class derived from Janitor // which does not include a copy constructor [ eg X(const &X) ]. // Possibly also if delete is applied an object on the stack (ie not // called by new). Otherwise, it is a bug in myexcept or your compiler. // If you do not #define TEMPS_DESTROYED_QUICKLY you will get this // error with Microsoft C 7.0. There are probably situations where // you will get this when you do define TEMPS_DESTROYED_QUICKLY. This // is a bug in MSC. Beware of "operator" statements for defining // conversions; particularly for converting from a Base class to a // Derived class. // You may get away with simply deleting this error message and Throw // statement if you can not find a better way of overcoming the // problem. In any case please tell me if you get this error message, // particularly for compilers apart from Microsoft C 7.0. } } }
/** GetThis Stage from GameObject */ shared_ptr<Stage> GameObject::GetStage() const { auto stageptr = pImpl->m_Stage.lock(); if (!stageptr) { throw BaseException( L"GameObjectは有効ではありません", L"sステージが存在しているか確認してください", L"GameObject::GetStage()" ); } else { return stageptr; } }
void SimpleSquare::OnUpdate() { float ElapsedTime = App::GetApp()->GetElapsedTime(); auto Dev = App::GetApp()->GetDeviceResources(); auto pD3D11DeviceContext = Dev->GetD3DDeviceContext(); //頂点の変更 //D3D11_MAP_WRITE_DISCARDは重要。この処理により、GPUに邪魔されない D3D11_MAP mapType = D3D11_MAP_WRITE_DISCARD; D3D11_MAPPED_SUBRESOURCE mappedBuffer; //頂点のマップ if (FAILED(pD3D11DeviceContext->Map(m_SquareMesh->GetVertexBuffer().Get(), 0, mapType, 0, &mappedBuffer))) { // Map失敗 throw BaseException( L"頂点のMapに失敗しました。", L"if(FAILED(pID3D11DeviceContext->Map()))", L"SimpleSquare::OnUpdate()" ); } //頂点の変更 VertexPositionColorTexture* vertices = (VertexPositionColorTexture*)mappedBuffer.pData; //関数呼び出し UpdateVertex(ElapsedTime, vertices); //アンマップ pD3D11DeviceContext->Unmap(m_SquareMesh->GetVertexBuffer().Get(), 0); auto PtrStage = GetStage<Stage>(); //カメラの位置 Vec3 CameraEye = PtrStage->GetCamera().m_CamerEye; Vec3 CameraAt = PtrStage->GetCamera().m_CamerAt; switch (m_DrawOption) { case SquareDrawOption::Billboard: { m_Qt.facing(CameraAt - CameraEye); } break; case SquareDrawOption::Faceing: { m_Qt.facing(m_Pos - CameraEye); } break; case SquareDrawOption::FaceingY: m_Qt.facingY(m_Pos - CameraEye); break; default: m_Qt.normalize(); break; } }
int main(int argc, char* argv[]) { /////////////////////////////////////////////////////// try { switch(argc) { case 2: config.set("Common", "TCPport", atoi(argv[1])); case 1: break; default: throw BaseException("incorrect number of arguments"); } } catch(const std::exception& e) { std::cerr<<"[main] Exception: "<<e.what()<<"."<<std::endl; std::cout<<"usage: ChatServer [hostIP]"<<std::endl; return 1; //failure } /////////////////////////////////////////////////////// try { std::cout<<config.str()<<std::endl; } catch(const std::exception& e) { std::cerr<<"[main] Exception: "<<e.what()<<"."<<std::endl; return 1; //failure } /////////////////////////////////////////////////////// try { int tcpPort=config.get<int>("Common", "TCPport"); boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), tcpPort); ChatServer chatServer(endpoint); chatServer.accept(); //async chatServer.run(); } catch(const std::exception& e) { std::cerr<<"[main] Exception: "<<e.what()<<std::endl; } /////////////////////////////////////////////////////// return 0; //success }
//シングルトンアクセサ unique_ptr<App, App::AppDeleter>& App::GetApp() { try { if (m_App.get() == 0) { throw BaseException( L"アプリケーションがまだ作成されてません", L"if (m_App.get() == 0)", L"App::GetApp()" ); } return m_App; } catch (...) { throw; } }
//タイリングプレートの作成 void GameStage::CreatePlate() { auto PlateNode = m_XmlDocReader->GetSelectSingleNode(L"GameStage/GameObjects/TilingPlate"); if (!PlateNode) { throw BaseException( L"GameStage/GameObjects/TilingPlateが見つかりません", L"if (!PlateNode)", L"GameStage::CreatePlate()" ); } //トークン(カラム)の配列 vector<wstring> Tokens; auto ScaleNode = XmlDocReader::GetSelectSingleNode(PlateNode, L"Scale"); auto RotNode = XmlDocReader::GetSelectSingleNode(PlateNode, L"Rot"); auto PosNode = XmlDocReader::GetSelectSingleNode(PlateNode, L"Pos"); wstring ScaleStr = XmlDocReader::GetText(ScaleNode); wstring RotStr = XmlDocReader::GetText(RotNode); wstring PosStr = XmlDocReader::GetText(PosNode); //トークン(カラム)単位で文字列を抽出(L','をデリミタとして区分け) Tokens.clear(); Util::WStrToTokenVector(Tokens, ScaleStr, L','); //各トークン(カラム)をスケール、回転、位置に読み込む Vec3 Scale( (float)_wtof(Tokens[0].c_str()), (float)_wtof(Tokens[1].c_str()), (float)_wtof(Tokens[2].c_str()) ); Tokens.clear(); Util::WStrToTokenVector(Tokens, RotStr, L','); Vec3 Rot; //回転は「XM_PIDIV2」の文字列になっている場合がある Rot.x = (Tokens[0] == L"XM_PIDIV2") ? XM_PIDIV2 : (float)_wtof(Tokens[0].c_str()); Rot.y = (Tokens[1] == L"XM_PIDIV2") ? XM_PIDIV2 : (float)_wtof(Tokens[1].c_str()); Rot.z = (Tokens[2] == L"XM_PIDIV2") ? XM_PIDIV2 : (float)_wtof(Tokens[2].c_str()); Tokens.clear(); Util::WStrToTokenVector(Tokens, PosStr, L','); Vec3 Pos( (float)_wtof(Tokens[0].c_str()), (float)_wtof(Tokens[1].c_str()), (float)_wtof(Tokens[2].c_str()) ); //プレートの回転の引数はクオータニオンになっているので変換 Quat Qt; Qt.rotationRollPitchYawFromVector(Rot); //ステージへのゲームオブジェクトの追加 AddGameObject<TilingPlate>(Scale, Qt, Pos, 1.0f, 1.0f); }
//ボックスの作成 void GameStage::CreateFixedBox() { auto BoxNodes = m_XmlDocReader->GetSelectNodes(L"GameStage/GameObjects/TilingFixedBox"); if (!BoxNodes) { throw BaseException( L"GameStage/GameObjects/TilingFixedBoxが見つかりません", L"if (!BoxNodes)", L"GameStage::CreateFixedBox()" ); } long CountNode = XmlDocReader::GetLength(BoxNodes); for (long i = 0; i < CountNode; i++) { auto Node = XmlDocReader::GetItem(BoxNodes, i); auto ScaleNode = XmlDocReader::GetSelectSingleNode(Node, L"Scale"); auto RotNode = XmlDocReader::GetSelectSingleNode(Node, L"Rot"); auto PosNode = XmlDocReader::GetSelectSingleNode(Node,L"Pos"); wstring ScaleStr = XmlDocReader::GetText(ScaleNode); wstring RotStr = XmlDocReader::GetText(RotNode); wstring PosStr = XmlDocReader::GetText(PosNode); //トークン(カラム)の配列 vector<wstring> Tokens; //トークン(カラム)単位で文字列を抽出(L','をデリミタとして区分け) Util::WStrToTokenVector(Tokens, ScaleStr, L','); //各トークン(カラム)をスケール、回転、位置に読み込む Vec3 Scale( (float)_wtof(Tokens[0].c_str()), (float)_wtof(Tokens[1].c_str()), (float)_wtof(Tokens[2].c_str()) ); Tokens.clear(); Util::WStrToTokenVector(Tokens, RotStr, L','); Vec3 Rot; //回転は「XM_PIDIV2」の文字列になっている場合がある Rot.x = (Tokens[0] == L"XM_PIDIV2") ? XM_PIDIV2 : (float)_wtof(Tokens[0].c_str()); Rot.y = (Tokens[1] == L"XM_PIDIV2") ? XM_PIDIV2 : (float)_wtof(Tokens[1].c_str()); Rot.z = (Tokens[2] == L"XM_PIDIV2") ? XM_PIDIV2 : (float)_wtof(Tokens[2].c_str()); Tokens.clear(); Util::WStrToTokenVector(Tokens, PosStr, L','); Vec3 Pos( (float)_wtof(Tokens[0].c_str()), (float)_wtof(Tokens[1].c_str()), (float)_wtof(Tokens[2].c_str()) ); //各値がそろったのでオブジェクト作成 AddGameObject<TilingFixedBox>(Scale, Rot, Pos, 1.0f, 1.0f); } }
void WriteToFile::Execute(std::vector<boost::any> arglist) { std::string lineToWrite; try{ std::string path = boost::any_cast<std::string>(arglist[0]); try{ lineToWrite = boost::any_cast<std::string>(arglist[1]); } catch (std::exception& e) { lineToWrite = std::to_string(boost::any_cast<double>(arglist[1])); } std::ofstream out; out.open(path, std::ios::app); out << lineToWrite << std::endl; out.close(); } catch (std::exception& e){ throw BaseException("WriteToFile kan geen booleans wegschrijven"); } }
//敵の作成 void GameStage::CreateEnemy() { //オブジェクトのグループを作成する auto Group = CreateSharedObjectGroup(L"EnemyGroup"); //セルマップのノードを取得 auto CellmapNode = m_XmlDocReader->GetSelectSingleNode(L"GameStage/CellMap"); if (!CellmapNode) { throw BaseException( L"GameStage/CellMapが見つかりません", L"if (!CellmapNode)", L"GameStage::CreateEnemy()" ); } //内容の文字列を取得 wstring MapStr = XmlDocReader::GetText(CellmapNode); vector<wstring> LineVec; //最初に「改行」をデリミタとした文字列の配列にする Util::WStrToTokenVector(LineVec, MapStr, L'\n'); for (size_t i = 0; i < LineVec.size();i++) { //トークン(カラム)の配列 vector<wstring> Tokens; //トークン(カラム)単位で文字列を抽出(L','をデリミタとして区分け) Util::WStrToTokenVector(Tokens, LineVec[i], L','); for (size_t j = 0; j < Tokens.size(); j++) { //XとZの位置を計算 float XPos = (float)((int)j - 19); float ZPos = (float)(19 - (int)i); if (Tokens[j] == L"1") { AddGameObject<Enemy1>(Vec3(XPos,0.25f,ZPos)); } else if (Tokens[j] == L"2") { AddGameObject<Enemy2>(Vec3(XPos, 0.25f, ZPos)); } else if (Tokens[j] == L"3") { AddGameObject<Enemy3>(Vec3(XPos, 0.25f, ZPos)); } } } }
//-------------------------------------------------------------------------------------- // void RenderState::Impl::CreateDepthStencilState( // bool enable, // bool writeEnable, // ID3D11DepthStencilState** pResult // ); // 用途: デプスステンシルステートを作成するヘルパー関数 // 戻り値: なし //-------------------------------------------------------------------------------------- void RenderState::Impl::CreateDepthStencilState(bool enable, bool writeEnable, ID3D11DepthStencilState** pResult){ try{ auto Dev = App::GetApp()->GetDeviceResources(); auto pDx11Device = Dev->GetD3DDevice(); D3D11_DEPTH_STENCIL_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.DepthEnable = enable; desc.DepthWriteMask = writeEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; desc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; desc.StencilEnable = false; desc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; desc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; desc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; desc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; desc.BackFace = desc.FrontFace; HRESULT hr = pDx11Device->CreateDepthStencilState(&desc, pResult); if (FAILED(hr)){ // 初期化失敗 throw BaseException( L"デプスステンシルステート作成に失敗しました。", L"if(FAILED(pDx11Device->CreateDepthStencilState()))", L"RenderState::Impl::CreateDepthStencilState()" ); } } catch (...){ throw; } }
//-------------------------------------------------------------------------------------- // void RenderState::Impl::CreateSamplerState( // D3D11_FILTER filter, //フィルター // D3D11_TEXTURE_ADDRESS_MODE addressMode //アドレスモード // ID3D11SamplerState** pResult //受け取るインターフェイス // ); // 用途: サンプラーステートを作成するヘルパー関数 // 戻り値: なし //-------------------------------------------------------------------------------------- void RenderState::Impl::CreateSamplerState(D3D11_FILTER filter, D3D11_TEXTURE_ADDRESS_MODE addressMode, ID3D11SamplerState** pResult){ try{ auto Dev = App::GetApp()->GetDeviceResources(); auto pDx11Device = Dev->GetD3DDevice(); D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Filter = filter; desc.AddressU = addressMode; desc.AddressV = addressMode; desc.AddressW = addressMode; desc.MaxAnisotropy = (pDx11Device->GetFeatureLevel() > D3D_FEATURE_LEVEL_9_1) ? 16 : 2; desc.MaxLOD = FLT_MAX; desc.ComparisonFunc = D3D11_COMPARISON_NEVER; HRESULT hr = pDx11Device->CreateSamplerState(&desc, pResult); if (FAILED(hr)){ // 初期化失敗 throw BaseException( L"サンプラーステート作成に失敗しました。", L"if(FAILED(pDx11Device->CreateSamplerState()))", L"RenderState::Impl::CreateSamplerState()" ); } } catch (...){ throw; } }
//初期化 void Enemy::OnCreate() { auto PtrTransform = GetComponent<Transform>(); PtrTransform->SetPosition(m_StartPosition); PtrTransform->SetScale(m_Scale); PtrTransform->SetRotation(m_StartRotation); //Rigidbodyをつける auto PtrRigid = AddComponent<Rigidbody>(); //パス検索 auto MapPtr = m_CelMap.lock(); if (!MapPtr) { throw BaseException( L"セルマップが不定です", L"if (!MapPtr) ", L" Enemy::OnCreate()" ); } auto PathPtr = AddComponent<PathSearch>(MapPtr); //SPの衝突判定をつける auto PtrColl = AddComponent<CollisionSphere>(); PtrColl->SetIsHitAction(IsHitAction::Auto); //影をつける auto ShadowPtr = AddComponent<Shadowmap>(); ShadowPtr->SetMeshResource(L"DEFAULT_SPHERE"); auto PtrDraw = AddComponent<BcPNTStaticDraw>(); PtrDraw->SetFogEnabled(true); PtrDraw->SetMeshResource(L"DEFAULT_SPHERE"); PtrDraw->SetTextureResource(L"TRACE2_TX"); //透明処理をする SetAlphaActive(true); m_StateMachine = make_shared<StateMachine<Enemy>>(GetThis<Enemy>()); m_StateMachine->ChangeState(EnemyDefault::Instance()); }
//-------------------------------------------------------------------------------------- // class DefaultRenderTarget : public RenderTarget; // 用途: デフォルトのレンダーターゲット // *デフォルトのレンダラー //-------------------------------------------------------------------------------------- //構築 DefaultRenderTarget::DefaultRenderTarget(const shared_ptr<Stage>& stage) : pImpl(new Impl(stage)) { try{ if (pImpl->m_Stage.expired()){ throw BaseException( L"ステージが無効です", L"if (pImpl->m_Stage.expired())", L"DefaultRenderTarget::DefaultRenderTarget()" ); } auto Dev = App::GetApp()->GetDeviceResources(); auto pD3D11Device = Dev->GetD3DDevice(); auto pSwapChain = Dev->GetSwapChain(); auto pD3D11DeviceContext = Dev->GetD3DDeviceContext(); auto pD2D11DeviceContext = Dev->GetD2DDeviceContext(); //レンダリングターゲットビューの作成 ComPtr<ID3D11Texture2D> pBackBuffer; //まずバックバッファのポインタを得る ThrowIfFailed( pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer), L"スワップチェーンからバックバッファの取得に失敗しました。", L"pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer)", L"DefaultRenderTarget::DefaultRenderTarget()" ); //バックバッファからレンダリングターゲットのビューを作成する ThrowIfFailed( pD3D11Device->CreateRenderTargetView(pBackBuffer.Get(), nullptr, &pImpl->m_D3D11RenderTargetView), L"DX11バックバッファからのレンダリングターゲットビューを作成に失敗しました。", L"pD3D11Device->CreateRenderTargetView(pBackBuffer.Get(), nullptr, &m_D3D11RenderTargetView)", L"DefaultRenderTarget::DefaultRenderTarget()" ); //深度テクスチャの作成 D3D11_TEXTURE2D_DESC descDepth; ZeroMemory(&descDepth, sizeof(descDepth)); descDepth.Width = App::GetApp()->GetGameWidth(); descDepth.Height = App::GetApp()->GetGameHeight(); descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepth.SampleDesc.Count = 1; descDepth.SampleDesc.Quality = 0; descDepth.Usage = D3D11_USAGE_DEFAULT; descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; ThrowIfFailed( pD3D11Device->CreateTexture2D(&descDepth, nullptr, &pImpl->m_DepthStencil), L"DX11深度テクスチャの作成失敗の作成に失敗しました。", L"pD3D11Device->CreateTexture2D(&descDepth, nullptr, &m_DepthStencil)", L"DefaultRenderTarget::DefaultRenderTarget()" ); //深度ステンシルビューの作成 D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; ZeroMemory(&descDSV, sizeof(descDSV)); descDSV.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; ThrowIfFailed( pD3D11Device->CreateDepthStencilView(pImpl->m_DepthStencil.Get(), &descDSV, &pImpl->m_DepthStencilView), L"DX11深度ステンシルビューの作成に失敗しました。", L"pD3D11Device->CreateDepthStencilView(m_DepthStencil.Get(), &descDSV, &m_DepthStencilView)", L"DefaultRenderTarget::DefaultRenderTarget()" ); ComPtr<IDXGISurface2> dxgiBackBuffer; ThrowIfFailed( pSwapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer)), L"2dデバイスコンテキスト作成に失敗しました。", L"m_d2dDevice->CreateDeviceContext()", L"DeviceResources::Impl::CreateDeviceResources()" ); ThrowIfFailed( pD2D11DeviceContext->CreateBitmapFromDxgiSurface( dxgiBackBuffer.Get(), nullptr, //デフォルト設定 &pImpl->m_d2dTargetBitmap ), L"2dビットマップ作成に失敗しました。", L"pD2D11DeviceContext->CreateBitmapFromDxgiSurface()", L"DefaultRenderTarget::DefaultRenderTarget()" ); pD2D11DeviceContext->SetTarget(pImpl->m_d2dTargetBitmap.Get()); //グレースケール テキストのアンチエイリアシング pD2D11DeviceContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE); } catch (...){ throw; } }
void test4(int n) { cout << endl << endl; cout << "Combinations and permutations" << endl; cout << endl; cout << "Just checking that we get a valid permutation or combination" << endl; { cout << "Doing permutations" << endl; RandomPermutation RP; int i, j, k; int p[10]; cout << "... select 10 items from 100...119 without replacement" << endl; for (i = 1; i <= 10; i++) { RP.Next(20,10,p,100); for (j = 0; j < 10; j++) { int pj = p[j]; if (pj < 100 || pj > 119) Throw(BaseException("Invalid permutation generated")); for (k = 0; k < j; ++k) if (p[k] == pj) Throw(BaseException("Invalid permutation generated")); } } cout << "... select 10 items from 100...109 without replacement" << endl; for (i = 1; i <= 10; i++) { RP.Next(10,10,p,100); for (j = 0; j < 10; j++) { int pj = p[j]; //cout << pj << " "; if (pj < 100 || pj > 109) Throw(BaseException("Invalid permutation generated")); for (k = 0; k < j; ++k) if (p[k] == pj) Throw(BaseException("Invalid permutation generated")); } } } { cout << "Doing combinations" << endl; RandomCombination RC; int i, j; int p[10]; cout << "... select 10 items from 100...119 without replacement" << endl; for (i = 1; i <= 10; i++) { RC.Next(20,10,p,100); for (j = 0; j < 10; j++) { int pj = p[j]; if (pj < 100 || pj > 119) Throw(BaseException("Invalid permutation generated")); if (j > 0 && pj <= p[j-1]) Throw(BaseException("Invalid permutation generated")); } } cout << "... select 10 items from 100...109 without replacement" << endl; for (i = 1; i <= 10; i++) { RC.Next(10,10,p,100); for (j = 0; j < 10; j++) { int pj = p[j]; //cout << pj << " "; if (pj < 100 || pj > 109) Throw(BaseException("Invalid permutation generated")); if (j > 0 && pj <= p[j-1]) Throw(BaseException("Invalid permutation generated")); } //cout << "\n"; } //cout << "\n"; } cout << endl; cout << "Doing formal tests of permutation generator" << endl; cout << endl; cout << "Carries out a number of tests which generate approximately" << endl; cout << "normally distributed test statistics;" << endl; cout << "param. 1 and param. 2 show the mean and s.d. of the test statistic;" << endl; cout << "statistic shows the test statistic value;" << endl; cout << "n. stat shows the normalised value;" << endl; cout << "-lg sig shows -log10 of the significance probability." << endl; cout << "Should be less than 1.3 (5% sig) in most cases and" << endl; cout << "2 (1% sig) in almost all cases." << endl; cout << endl; cout << "* shows 5% significance; ** shows 1% significance;" << endl; cout << "*** shows 0.1% significance." << endl; test_perm(1, 10, n * 10); test_perm(4, 10, n * 10); test_perm(7, 10, n * 10); test_perm(10, 10, n * 10); test_perm(1, 100, n); test_perm(30, 100, n); test_perm(65, 100, n); test_perm(100, 100, n); test_perm(100, 1000, n / 10); }
//メッシュデータの読み込み void GameObject::ReadMesh(vector<VertexPositionNormalTexture>& vertices, vector<uint16_t>& indices, vector<MaterialEx>& materials){ auto MeshFileName = App::GetApp()->m_wstrRelativeDataPath + L"Chara_R.bin"; BinaryReader Reader(MeshFileName); //ヘッダの読み込み auto pHeader = Reader.ReadArray<char>(16); string str = pHeader; if (str != "BDV1.0"){ throw BaseException( L"データ形式が違います", MeshFileName, L"GameObject::ReadMesh()" ); } //頂点の読み込み auto blockHeader = Reader.Read<BlockHeader>(); if (blockHeader.m_Type != BlockType::Vertex){ throw BaseException( L"頂点のヘッダが違います", MeshFileName, L"GameObject::ReadMesh()" ); } auto VerTexSize = blockHeader.m_Size / sizeof(VertexPositionNormalTexturePOD); auto pVertex = Reader.ReadArray<VertexPositionNormalTexturePOD>((size_t)VerTexSize); for (UINT i = 0; i < VerTexSize; i++){ VertexPositionNormalTexture v; v.position.x = pVertex[i].position[0]; v.position.y = pVertex[i].position[1]; v.position.z = pVertex[i].position[2]; v.normal.x = pVertex[i].normal[0]; v.normal.y = pVertex[i].normal[1]; v.normal.z = pVertex[i].normal[2]; v.textureCoordinate.x = pVertex[i].textureCoordinate[0]; v.textureCoordinate.y = pVertex[i].textureCoordinate[1]; vertices.push_back(v); } //インデックスの読み込み blockHeader = Reader.Read<BlockHeader>(); if (blockHeader.m_Type != BlockType::Index){ throw BaseException( L"インデックスのヘッダが違います", MeshFileName, L"GameObject::ReadMesh()" ); } auto IndexSize = blockHeader.m_Size / sizeof(uint16_t); auto pIndex = Reader.ReadArray<uint16_t>((size_t)IndexSize); for (UINT i = 0; i < IndexSize; i++){ indices.push_back(pIndex[i]); } //マテリアルの読み込み //マテリアル数の読み込み blockHeader = Reader.Read<BlockHeader>(); if (blockHeader.m_Type != BlockType::MaterialCount){ throw BaseException( L"マテリアル数のヘッダが違います", MeshFileName, L"GameObject::ReadMesh()" ); } UINT MaterialCount = blockHeader.m_Size; for (UINT i = 0; i < MaterialCount; i++){ //テクスチャファイル名が可変長なので注意。 blockHeader = Reader.Read<BlockHeader>(); if (blockHeader.m_Type != BlockType::Material){ throw BaseException( L"マテリアルのヘッダが違います", MeshFileName, L"GameObject::ReadMesh()" ); } UINT TextureFileNameSize = blockHeader.m_Size - sizeof(MaterialExPOD); auto rMaterial = Reader.Read<MaterialExPOD>(); MaterialEx ToM; //!開始インデックス ToM.m_StartIndex = rMaterial.m_StartIndex; //!描画インデックスカウント ToM.m_IndexCount = rMaterial.m_IndexCount; //! デフィーズ(物体の色) ToM.m_Diffuse.x = rMaterial.m_Diffuse[0]; ToM.m_Diffuse.y = rMaterial.m_Diffuse[1]; ToM.m_Diffuse.z = rMaterial.m_Diffuse[2]; ToM.m_Diffuse.w = rMaterial.m_Diffuse[3]; //! スペキュラー(反射光) ToM.m_Specular.x = rMaterial.m_Specular[0]; ToM.m_Specular.y = rMaterial.m_Specular[1]; ToM.m_Specular.z = rMaterial.m_Specular[2]; ToM.m_Specular.w = rMaterial.m_Specular[3]; //! アンビエント(環境色) ToM.m_Ambient.x = rMaterial.m_Ambient[0]; ToM.m_Ambient.y = rMaterial.m_Ambient[1]; ToM.m_Ambient.z = rMaterial.m_Ambient[2]; ToM.m_Ambient.w = rMaterial.m_Ambient[3]; //! エミッシブ(放射光) ToM.m_Emissive.x = rMaterial.m_Emissive[0]; ToM.m_Emissive.y = rMaterial.m_Emissive[1]; ToM.m_Emissive.z = rMaterial.m_Emissive[2]; ToM.m_Emissive.w = rMaterial.m_Emissive[3]; auto pTexture = Reader.ReadArray<wchar_t>(TextureFileNameSize / sizeof(wchar_t)); wstring TextureFileStr = pTexture; TextureFileStr = App::GetApp()->m_wstrRelativeDataPath + TextureFileStr; ToM.m_ShaderResView = CreateShaderResView(TextureFileStr); materials.push_back(ToM); } //Endの読み込み blockHeader = Reader.Read<BlockHeader>(); if (blockHeader.m_Type != BlockType::End){ throw BaseException( L"Endヘッダが違います", MeshFileName, L"GameObject::ReadMesh()" ); } }
const std::string& ClansManager::clanName(u16 id) const { std::map<u16,Clan>::const_iterator it = m_ids.find(id); if(it==m_ids.end()) throw BaseException("Clan doesn't exist"); return it->second.name; }
void PylosMove::operator=(const std::string &src) { char wd1[11], wd2[11], wd3[11], bk1, bk2, bk3, bk4, extra; std::pair<short, short> p1, p2, p3, p4; int res; short type; LocVector temp; sscanf(src.c_str(), "%10s", wd1); if (!strcmp(wd1, "Play")) { type = kReserve; res = sscanf(src.c_str(), " Play at [ %hd , %hd %c %6s [ %hd , %hd %c %3s" " [ %hd , %hd %c %c", &p1.first, &p1.second, &bk1, wd1, &p2.first, &p2.second, &bk2, wd2, &p3.first, &p3.second, &bk3, &extra); if (res == 3 && bk1 == ']' || res == 7 && bk1 == ']' && bk2 == ']' && !strcmp(wd1, "taking") || res == 11 && bk1 == ']' && bk2 == ']' && bk3 == ']' && !strcmp(wd1, "taking") && !strcmp(wd2, "and")) { temp.push_back(p1); if (res >= 7) temp.push_back(p2); if (res == 11) temp.push_back(p3); } else { throw BaseException(FString("Bad Pylos move: %s", src.c_str())); } } else if (!strcmp(wd1, "Promote")) { type = kPromote; res = sscanf(src.c_str(), " Promote from [ %hd , %hd %c %2s [ %hd , %hd " "%c %6s [ %hd , %hd %c %3s [ %hd , %hd %c %c", &p1.first, &p1.second, &bk1, wd1, &p2.first, &p2.second, &bk2, wd2, &p3.first, &p3.second, &bk3, wd3, &p4.first, &p4.second, &bk4, &extra); if (res == 7 && bk1 == ']' && bk2 == ']' && !strcmp(wd1, "to") || res == 11 && bk1 == ']' && bk2 == ']' && bk3 == ']' && !strcmp(wd1, "to") && !strcmp(wd2, "taking") || res == 15 && bk1 == ']' && bk2 == ']' && bk3 == ']' && bk4 == ']' && !strcmp(wd1, "to") && !strcmp(wd2, "taking") && !strcmp(wd3, "and")) { temp.push_back(p2); temp.push_back(p1); if (res >= 11) temp.push_back(p3); if (res == 15) temp.push_back(p4); } else { throw BaseException(FString("Bad Pylos move: %s", src.c_str())); } } else { throw BaseException(FString("Bad Pylos move: %s", src.c_str())); } for (LocVector::const_iterator iter = temp.begin(); iter != temp.end(); iter++) { if (!InRange<short>(0, iter->first, PylosBoard::kDim) || !InRange<short>(0, iter->second, PylosBoard::kDim)) { throw BaseException(FString("Out of bounds Pylos move: %s", src.c_str())); } } mType = type; mLocs = temp; }
//構築 App::App(HINSTANCE hInstance, HWND hWnd, bool FullScreen, UINT Width, UINT Height) : m_hInstance{ hInstance }, m_hWnd{ hWnd }, m_FullScreen{ FullScreen }, m_GameWidth{ Width }, m_GameHeight{ Height }, m_Timer() { try { //基準ディレクトリの設定 //相対パスにすると、ファイルダイアログでカレントパスが狂うので //絶対パス指定 wchar_t Modulebuff[MAX_PATH]; wchar_t Drivebuff[_MAX_DRIVE]; wchar_t Dirbuff[_MAX_DIR]; wchar_t FileNamebuff[_MAX_FNAME]; wchar_t Extbuff[_MAX_EXT]; ::ZeroMemory(Modulebuff, sizeof(Modulebuff)); ::ZeroMemory(Drivebuff, sizeof(Drivebuff)); ::ZeroMemory(Dirbuff, sizeof(Dirbuff)); ::ZeroMemory(FileNamebuff, sizeof(FileNamebuff)); ::ZeroMemory(Extbuff, sizeof(Extbuff)); //モジュール名(プログラムファイル名)を得る if (!::GetModuleFileName(nullptr, Modulebuff, sizeof(Modulebuff))) { throw BaseException( L"モジュールが取得できません。", L"if(!::GetModuleFileName())", L"App::App()" ); } m_wstrModulePath = Modulebuff; //モジュール名から、各ブロックに分ける _wsplitpath_s(Modulebuff, Drivebuff, _MAX_DRIVE, Dirbuff, _MAX_DIR, FileNamebuff, _MAX_FNAME, Extbuff, _MAX_EXT); //ドライブ名の取得 m_wstrDir = Drivebuff; //ディレクトリ名の取得 m_wstrDir += Dirbuff; //mediaディレクトリを探す m_wstrDataPath = m_wstrDir; m_wstrDataPath += L"media"; //まず、実行ファイルと同じディレクトリを探す DWORD RetCode; RetCode = GetFileAttributes(m_wstrDataPath.c_str()); if (RetCode == 0xFFFFFFFF) { //失敗した m_wstrDataPath = m_wstrDir; m_wstrDataPath += L"..\\media"; RetCode = GetFileAttributes(m_wstrDataPath.c_str()); if (RetCode == 0xFFFFFFFF) { //再び失敗した throw BaseException( L"mediaディレクトリを確認できません。", L"if(RetCode == 0xFFFFFFFF)", L"App::App()" ); } else { m_wstrDataPath += L"\\"; //相対パスの設定 m_wstrRelativeDataPath = L"..\\media\\"; } } else { m_wstrDataPath += L"\\"; //相対パスの設定 m_wstrRelativeDataPath = L"media\\"; } m_wstrShadersPath = m_wstrDataPath + L"Shaders\\"; m_wstrRelativeShadersPath = m_wstrRelativeDataPath + L"Shaders\\"; ////デバイスリソースの構築 m_DeviceResources = shared_ptr<DeviceResources>(new DeviceResources(hWnd, FullScreen, Width, Height)); m_DeviceResources->AfterInitContents(); //オーディオマネージャの取得 GetAudioManager(); //乱数の初期化 srand((unsigned)time(nullptr)); } catch (...) { throw; } }