CGameInterface.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "stdafx.h"
  2. #include "CGameInterface.h"
  3. #include "lib/BattleState.h"
  4. #ifdef _WIN32
  5. #define WIN32_LEAN_AND_MEAN //excludes rarely used stuff from windows headers - delete this line if something is missing
  6. #include <windows.h> //for .dll libs
  7. #else
  8. #include <dlfcn.h>
  9. #endif
  10. /*
  11. * CGameInterface.cpp, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. template<typename rett>
  20. rett * createAnyAI(CCallback * cb, std::string dllname, std::string methodName)
  21. {
  22. char temp[50];
  23. rett * ret=NULL;
  24. rett*(*getAI)();
  25. void(*getName)(char*);
  26. std::string dllPath;
  27. #ifdef _WIN32
  28. dllPath = LIB_DIR "/" +dllname+".dll";
  29. HINSTANCE dll = LoadLibraryA(dllPath.c_str());
  30. if (!dll)
  31. {
  32. tlog1 << "Cannot open AI library ("<<dllPath<<"). Throwing..."<<std::endl;
  33. throw new std::string("Cannot open AI library");
  34. }
  35. //int len = dllname.size()+1;
  36. getName = (void(*)(char*))GetProcAddress(dll,"GetAiName");
  37. getAI = (rett*(*)())GetProcAddress(dll,methodName.c_str());
  38. #else
  39. dllPath = LIB_DIR "/" + dllname + ".so";
  40. void *dll = dlopen(dllPath.c_str(), RTLD_LOCAL | RTLD_LAZY);
  41. if (!dll)
  42. {
  43. tlog1 << "Cannot open AI library ("<<dllPath<<"). Throwing..."<<std::endl;
  44. throw new std::string("Cannot open AI library");
  45. }
  46. getName = (void(*)(char*))dlsym(dll,"GetAiName");
  47. getAI = (rett*(*)())dlsym(dll,methodName.c_str());
  48. #endif
  49. getName(temp);
  50. tlog0 << "Loaded AI named " << temp << std::endl;
  51. ret = getAI();
  52. if(!ret)
  53. tlog1 << "Cannot get AI!\n";
  54. ret->dllName = dllname;
  55. return ret;
  56. }
  57. CGlobalAI * CAIHandler::getNewAI(CCallback * cb, std::string dllname)
  58. {
  59. return createAnyAI<CGlobalAI>(cb, dllname, "GetNewAI");
  60. }
  61. CBattleGameInterface * CAIHandler::getNewBattleAI( CCallback * cb, std::string dllname )
  62. {
  63. return createAnyAI<CBattleGameInterface>(cb, dllname, "GetNewBattleAI");
  64. }
  65. BattleAction CGlobalAI::activeStack( const CStack * stack )
  66. {
  67. BattleAction ba; ba.actionType = BattleAction::DEFEND;
  68. ba.stackNumber = stack->ID;
  69. return ba;
  70. }