Bot.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Text;
  30. using System.IO;
  31. using System.Reflection;
  32. using System.Threading;
  33. using System.Timers;
  34. using log4net;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Assets;
  37. using Nini.Config;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Console;
  40. using pCampBot.Interfaces;
  41. using Timer = System.Timers.Timer;
  42. namespace pCampBot
  43. {
  44. public class Bot
  45. {
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. public delegate void AnEvent(Bot callbot, EventType someevent); // event delegate for bot events
  48. /// <summary>
  49. /// Bot manager.
  50. /// </summary>
  51. public BotManager Manager { get; private set; }
  52. /// <summary>
  53. /// Bot config, passed from BotManager.
  54. /// </summary>
  55. private IConfig startupConfig;
  56. /// <summary>
  57. /// Behaviours implemented by this bot.
  58. /// </summary>
  59. /// <remarks>
  60. /// Lock this list before manipulating it.
  61. /// </remarks>
  62. public List<IBehaviour> Behaviours { get; private set; }
  63. /// <summary>
  64. /// Objects that the bot has discovered.
  65. /// </summary>
  66. /// <remarks>
  67. /// Returns a list copy. Inserting new objects manually will have no effect.
  68. /// </remarks>
  69. public Dictionary<UUID, Primitive> Objects
  70. {
  71. get
  72. {
  73. lock (m_objects)
  74. return new Dictionary<UUID, Primitive>(m_objects);
  75. }
  76. }
  77. private Dictionary<UUID, Primitive> m_objects = new Dictionary<UUID, Primitive>();
  78. /// <summary>
  79. /// Is this bot connected to the grid?
  80. /// </summary>
  81. public bool IsConnected { get; private set; }
  82. public string FirstName { get; private set; }
  83. public string LastName { get; private set; }
  84. public string Name { get; private set; }
  85. public string Password { get; private set; }
  86. public string LoginUri { get; private set; }
  87. public string saveDir;
  88. public string wear;
  89. public event AnEvent OnConnected;
  90. public event AnEvent OnDisconnected;
  91. /// <summary>
  92. /// Keep a track of the continuously acting thread so that we can abort it.
  93. /// </summary>
  94. private Thread m_actionThread;
  95. protected List<uint> objectIDs = new List<uint>();
  96. /// <summary>
  97. /// Random number generator.
  98. /// </summary>
  99. public Random Random { get; private set; }
  100. /// <summary>
  101. /// New instance of a SecondLife client
  102. /// </summary>
  103. public GridClient Client { get; private set; }
  104. /// <summary>
  105. /// Constructor
  106. /// </summary>
  107. /// <param name="bm"></param>
  108. /// <param name="behaviours">Behaviours for this bot to perform</param>
  109. /// <param name="firstName"></param>
  110. /// <param name="lastName"></param>
  111. /// <param name="password"></param>
  112. /// <param name="loginUri"></param>
  113. /// <param name="behaviours"></param>
  114. public Bot(
  115. BotManager bm, List<IBehaviour> behaviours,
  116. string firstName, string lastName, string password, string loginUri)
  117. {
  118. behaviours.ForEach(b => b.Initialize(this));
  119. Client = new GridClient();
  120. Random = new Random(Environment.TickCount);// We do stuff randomly here
  121. FirstName = firstName;
  122. LastName = lastName;
  123. Name = string.Format("{0} {1}", FirstName, LastName);
  124. Password = password;
  125. LoginUri = loginUri;
  126. Manager = bm;
  127. startupConfig = bm.Config;
  128. readconfig();
  129. Behaviours = behaviours;
  130. }
  131. //We do our actions here. This is where one would
  132. //add additional steps and/or things the bot should do
  133. private void Action()
  134. {
  135. while (true)
  136. lock (Behaviours)
  137. Behaviours.ForEach(
  138. b =>
  139. {
  140. // m_log.DebugFormat("[pCAMPBOT]: For {0} performing action {1}", Name, b.GetType());
  141. b.Action();
  142. Thread.Sleep(Random.Next(1000, 10000));
  143. }
  144. );
  145. }
  146. /// <summary>
  147. /// Read the Nini config and initialize
  148. /// </summary>
  149. public void readconfig()
  150. {
  151. wear = startupConfig.GetString("wear", "no");
  152. }
  153. /// <summary>
  154. /// Tells LibSecondLife to logout and disconnect. Raises the disconnect events once it finishes.
  155. /// </summary>
  156. public void shutdown()
  157. {
  158. if (m_actionThread != null)
  159. m_actionThread.Abort();
  160. Client.Network.Logout();
  161. }
  162. /// <summary>
  163. /// This is the bot startup loop.
  164. /// </summary>
  165. public void startup()
  166. {
  167. Client.Settings.LOGIN_SERVER = LoginUri;
  168. Client.Settings.ALWAYS_DECODE_OBJECTS = false;
  169. Client.Settings.AVATAR_TRACKING = false;
  170. Client.Settings.OBJECT_TRACKING = false;
  171. Client.Settings.SEND_AGENT_THROTTLE = true;
  172. Client.Settings.SEND_PINGS = true;
  173. Client.Settings.STORE_LAND_PATCHES = false;
  174. Client.Settings.USE_ASSET_CACHE = false;
  175. Client.Settings.MULTIPLE_SIMS = true;
  176. Client.Throttle.Asset = 100000;
  177. Client.Throttle.Land = 100000;
  178. Client.Throttle.Task = 100000;
  179. Client.Throttle.Texture = 100000;
  180. Client.Throttle.Wind = 100000;
  181. Client.Throttle.Total = 400000;
  182. Client.Network.LoginProgress += this.Network_LoginProgress;
  183. Client.Network.SimConnected += this.Network_SimConnected;
  184. Client.Network.Disconnected += this.Network_OnDisconnected;
  185. Client.Objects.ObjectUpdate += Objects_NewPrim;
  186. if (Client.Network.Login(FirstName, LastName, Password, "pCampBot", "Your name"))
  187. {
  188. IsConnected = true;
  189. Thread.Sleep(Random.Next(1000, 10000));
  190. m_actionThread = new Thread(Action);
  191. m_actionThread.Start();
  192. // OnConnected(this, EventType.CONNECTED);
  193. if (wear == "save")
  194. {
  195. Client.Appearance.SetPreviousAppearance();
  196. SaveDefaultAppearance();
  197. }
  198. else if (wear != "no")
  199. {
  200. MakeDefaultAppearance(wear);
  201. }
  202. // Extract nearby region information.
  203. Client.Grid.GridRegion += Manager.Grid_GridRegion;
  204. uint xUint, yUint;
  205. Utils.LongToUInts(Client.Network.CurrentSim.Handle, out xUint, out yUint);
  206. ushort minX, minY, maxX, maxY;
  207. minX = (ushort)Math.Min(0, xUint - 5);
  208. minY = (ushort)Math.Min(0, yUint - 5);
  209. maxX = (ushort)(xUint + 5);
  210. maxY = (ushort)(yUint + 5);
  211. Client.Grid.RequestMapBlocks(GridLayerType.Terrain, minX, minY, maxX, maxY, false);
  212. }
  213. else
  214. {
  215. m_log.ErrorFormat(
  216. "{0} {1} cannot login: {2}", FirstName, LastName, Client.Network.LoginMessage);
  217. if (OnDisconnected != null)
  218. {
  219. OnDisconnected(this, EventType.DISCONNECTED);
  220. }
  221. }
  222. }
  223. public void SaveDefaultAppearance()
  224. {
  225. saveDir = "MyAppearance/" + FirstName + "_" + LastName;
  226. if (!Directory.Exists(saveDir))
  227. {
  228. Directory.CreateDirectory(saveDir);
  229. }
  230. Array wtypes = Enum.GetValues(typeof(WearableType));
  231. foreach (WearableType wtype in wtypes)
  232. {
  233. UUID wearable = Client.Appearance.GetWearableAsset(wtype);
  234. if (wearable != UUID.Zero)
  235. {
  236. Client.Assets.RequestAsset(wearable, AssetType.Clothing, false, Asset_ReceivedCallback);
  237. Client.Assets.RequestAsset(wearable, AssetType.Bodypart, false, Asset_ReceivedCallback);
  238. }
  239. }
  240. }
  241. public void SaveAsset(AssetWearable asset)
  242. {
  243. if (asset != null)
  244. {
  245. try
  246. {
  247. if (asset.Decode())
  248. {
  249. File.WriteAllBytes(Path.Combine(saveDir, String.Format("{1}.{0}",
  250. asset.AssetType.ToString().ToLower(),
  251. asset.WearableType)), asset.AssetData);
  252. }
  253. else
  254. {
  255. m_log.WarnFormat("Failed to decode {0} asset {1}", asset.AssetType, asset.AssetID);
  256. }
  257. }
  258. catch (Exception e)
  259. {
  260. m_log.ErrorFormat("Exception: {0}{1}", e.Message, e.StackTrace);
  261. }
  262. }
  263. }
  264. public WearableType GetWearableType(string path)
  265. {
  266. string type = ((((path.Split('/'))[2]).Split('.'))[0]).Trim();
  267. switch (type)
  268. {
  269. case "Eyes":
  270. return WearableType.Eyes;
  271. case "Hair":
  272. return WearableType.Hair;
  273. case "Pants":
  274. return WearableType.Pants;
  275. case "Shape":
  276. return WearableType.Shape;
  277. case "Shirt":
  278. return WearableType.Shirt;
  279. case "Skin":
  280. return WearableType.Skin;
  281. default:
  282. return WearableType.Shape;
  283. }
  284. }
  285. public void MakeDefaultAppearance(string wear)
  286. {
  287. try
  288. {
  289. if (wear == "yes")
  290. {
  291. //TODO: Implement random outfit picking
  292. m_log.DebugFormat("Picks a random outfit. Not yet implemented.");
  293. }
  294. else if (wear != "save")
  295. saveDir = "MyAppearance/" + wear;
  296. saveDir = saveDir + "/";
  297. string[] clothing = Directory.GetFiles(saveDir, "*.clothing", SearchOption.TopDirectoryOnly);
  298. string[] bodyparts = Directory.GetFiles(saveDir, "*.bodypart", SearchOption.TopDirectoryOnly);
  299. InventoryFolder clothfolder = FindClothingFolder();
  300. UUID transid = UUID.Random();
  301. List<InventoryBase> listwearables = new List<InventoryBase>();
  302. for (int i = 0; i < clothing.Length; i++)
  303. {
  304. UUID assetID = UUID.Random();
  305. AssetClothing asset = new AssetClothing(assetID, File.ReadAllBytes(clothing[i]));
  306. asset.Decode();
  307. asset.Owner = Client.Self.AgentID;
  308. asset.WearableType = GetWearableType(clothing[i]);
  309. asset.Encode();
  310. transid = Client.Assets.RequestUpload(asset,true);
  311. Client.Inventory.RequestCreateItem(clothfolder.UUID, "MyClothing" + i.ToString(), "MyClothing", AssetType.Clothing,
  312. transid, InventoryType.Wearable, asset.WearableType, PermissionMask.All, delegate(bool success, InventoryItem item)
  313. {
  314. if (success)
  315. {
  316. listwearables.Add(item);
  317. }
  318. else
  319. {
  320. m_log.WarnFormat("Failed to create item {0}", item.Name);
  321. }
  322. }
  323. );
  324. }
  325. for (int i = 0; i < bodyparts.Length; i++)
  326. {
  327. UUID assetID = UUID.Random();
  328. AssetBodypart asset = new AssetBodypart(assetID, File.ReadAllBytes(bodyparts[i]));
  329. asset.Decode();
  330. asset.Owner = Client.Self.AgentID;
  331. asset.WearableType = GetWearableType(bodyparts[i]);
  332. asset.Encode();
  333. transid = Client.Assets.RequestUpload(asset,true);
  334. Client.Inventory.RequestCreateItem(clothfolder.UUID, "MyBodyPart" + i.ToString(), "MyBodyPart", AssetType.Bodypart,
  335. transid, InventoryType.Wearable, asset.WearableType, PermissionMask.All, delegate(bool success, InventoryItem item)
  336. {
  337. if (success)
  338. {
  339. listwearables.Add(item);
  340. }
  341. else
  342. {
  343. m_log.WarnFormat("Failed to create item {0}", item.Name);
  344. }
  345. }
  346. );
  347. }
  348. Thread.Sleep(1000);
  349. if (listwearables == null || listwearables.Count == 0)
  350. {
  351. m_log.DebugFormat("Nothing to send on this folder!");
  352. }
  353. else
  354. {
  355. m_log.DebugFormat("Sending {0} wearables...", listwearables.Count);
  356. Client.Appearance.WearOutfit(listwearables, false);
  357. }
  358. }
  359. catch (Exception ex)
  360. {
  361. Console.WriteLine(ex.ToString());
  362. }
  363. }
  364. public InventoryFolder FindClothingFolder()
  365. {
  366. UUID rootfolder = Client.Inventory.Store.RootFolder.UUID;
  367. List<InventoryBase> listfolders = Client.Inventory.Store.GetContents(rootfolder);
  368. InventoryFolder clothfolder = new InventoryFolder(UUID.Random());
  369. foreach (InventoryBase folder in listfolders)
  370. {
  371. if (folder.Name == "Clothing")
  372. {
  373. clothfolder = (InventoryFolder)folder;
  374. break;
  375. }
  376. }
  377. return clothfolder;
  378. }
  379. public void Network_LoginProgress(object sender, LoginProgressEventArgs args)
  380. {
  381. m_log.DebugFormat("[BOT]: Bot {0} {1} in Network_LoginProcess", Name, args.Status);
  382. if (args.Status == LoginStatus.Success)
  383. {
  384. if (OnConnected != null)
  385. {
  386. OnConnected(this, EventType.CONNECTED);
  387. }
  388. }
  389. }
  390. public void Network_SimConnected(object sender, SimConnectedEventArgs args)
  391. {
  392. m_log.DebugFormat(
  393. "[BOT]: Bot {0} connected to {1} at {2}", Name, args.Simulator.Name, args.Simulator.IPEndPoint);
  394. }
  395. public void Network_OnDisconnected(object sender, DisconnectedEventArgs args)
  396. {
  397. m_log.DebugFormat(
  398. "[BOT]: Bot {0} disconnected reason {1}, message {2}", Name, args.Reason, args.Message);
  399. // m_log.ErrorFormat("Fired Network_OnDisconnected");
  400. // if (
  401. // (args.Reason == NetworkManager.DisconnectType.SimShutdown
  402. // || args.Reason == NetworkManager.DisconnectType.NetworkTimeout)
  403. // && OnDisconnected != null)
  404. if (
  405. (args.Reason == NetworkManager.DisconnectType.ClientInitiated
  406. || args.Reason == NetworkManager.DisconnectType.ServerInitiated
  407. || args.Reason == NetworkManager.DisconnectType.NetworkTimeout)
  408. && OnDisconnected != null)
  409. // if (OnDisconnected != null)
  410. {
  411. IsConnected = false;
  412. OnDisconnected(this, EventType.DISCONNECTED);
  413. }
  414. }
  415. public void Objects_NewPrim(object sender, PrimEventArgs args)
  416. {
  417. Primitive prim = args.Prim;
  418. if (prim != null)
  419. {
  420. lock (m_objects)
  421. m_objects[prim.ID] = prim;
  422. if (prim.Textures != null)
  423. {
  424. if (prim.Textures.DefaultTexture.TextureID != UUID.Zero)
  425. {
  426. GetTexture(prim.Textures.DefaultTexture.TextureID);
  427. }
  428. for (int i = 0; i < prim.Textures.FaceTextures.Length; i++)
  429. {
  430. Primitive.TextureEntryFace face = prim.Textures.FaceTextures[i];
  431. if (face != null)
  432. {
  433. UUID textureID = prim.Textures.FaceTextures[i].TextureID;
  434. if (textureID != UUID.Zero)
  435. GetTexture(textureID);
  436. }
  437. }
  438. }
  439. if (prim.Sculpt != null && prim.Sculpt.SculptTexture != UUID.Zero)
  440. GetTexture(prim.Sculpt.SculptTexture);
  441. }
  442. }
  443. private void GetTexture(UUID textureID)
  444. {
  445. lock (Manager.AssetsReceived)
  446. {
  447. // Don't request assets more than once.
  448. if (Manager.AssetsReceived.ContainsKey(textureID))
  449. return;
  450. Manager.AssetsReceived[textureID] = false;
  451. Client.Assets.RequestImage(textureID, ImageType.Normal, Asset_TextureCallback_Texture);
  452. }
  453. }
  454. public void Asset_TextureCallback_Texture(TextureRequestState state, AssetTexture assetTexture)
  455. {
  456. //TODO: Implement texture saving and applying
  457. }
  458. public void Asset_ReceivedCallback(AssetDownload transfer, Asset asset)
  459. {
  460. lock (Manager.AssetsReceived)
  461. Manager.AssetsReceived[asset.AssetID] = true;
  462. // if (wear == "save")
  463. // {
  464. // SaveAsset((AssetWearable) asset);
  465. // }
  466. }
  467. }
  468. }