RecipeController.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package net.sf.l2j.gameserver;
  16. import java.io.File;
  17. import java.io.IOException;
  18. import java.util.Arrays;
  19. import java.util.Collections;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.WeakHashMap;
  23. import java.util.logging.Level;
  24. import java.util.logging.Logger;
  25. import javax.xml.parsers.DocumentBuilderFactory;
  26. import javax.xml.parsers.ParserConfigurationException;
  27. import javolution.util.FastList;
  28. import javolution.util.FastMap;
  29. import net.sf.l2j.Config;
  30. import net.sf.l2j.gameserver.model.Inventory;
  31. import net.sf.l2j.gameserver.model.L2ItemInstance;
  32. import net.sf.l2j.gameserver.model.L2ManufactureItem;
  33. import net.sf.l2j.gameserver.model.L2RecipeInstance;
  34. import net.sf.l2j.gameserver.model.L2RecipeList;
  35. import net.sf.l2j.gameserver.model.L2Skill;
  36. import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
  37. import net.sf.l2j.gameserver.network.SystemMessageId;
  38. import net.sf.l2j.gameserver.serverpackets.ActionFailed;
  39. import net.sf.l2j.gameserver.serverpackets.ItemList;
  40. import net.sf.l2j.gameserver.serverpackets.MagicSkillUse;
  41. import net.sf.l2j.gameserver.serverpackets.RecipeBookItemList;
  42. import net.sf.l2j.gameserver.serverpackets.RecipeItemMakeInfo;
  43. import net.sf.l2j.gameserver.serverpackets.RecipeShopItemInfo;
  44. import net.sf.l2j.gameserver.serverpackets.SetupGauge;
  45. import net.sf.l2j.gameserver.serverpackets.StatusUpdate;
  46. import net.sf.l2j.gameserver.serverpackets.SystemMessage;
  47. import net.sf.l2j.gameserver.skills.Stats;
  48. import net.sf.l2j.gameserver.util.Util;
  49. import net.sf.l2j.util.Rnd;
  50. import org.w3c.dom.Document;
  51. import org.w3c.dom.NamedNodeMap;
  52. import org.w3c.dom.Node;
  53. import org.xml.sax.SAXException;
  54. public class RecipeController
  55. {
  56. protected static final Logger _log = Logger.getLogger(RecipeController.class.getName());
  57. private static RecipeController _instance;
  58. private Map<Integer, L2RecipeList> _lists;
  59. protected static final Map<L2PcInstance, RecipeItemMaker> _activeMakers = Collections.synchronizedMap(new WeakHashMap<L2PcInstance, RecipeItemMaker>());
  60. private static final String RECIPES_FILE = "recipes.xml";
  61. public static RecipeController getInstance()
  62. {
  63. return _instance == null ? _instance = new RecipeController() : _instance;
  64. }
  65. public RecipeController()
  66. {
  67. _lists = new FastMap<Integer, L2RecipeList>();
  68. try
  69. {
  70. this.loadFromXML();
  71. _log.info("RecipeController: Loaded "+_lists.size()+" recipes.");
  72. }
  73. catch (Exception e)
  74. {
  75. _log.log(Level.SEVERE, "Failed loading recipe list", e);
  76. }
  77. }
  78. public int getRecipesCount()
  79. {
  80. return _lists.size();
  81. }
  82. public L2RecipeList getRecipeList(int listId)
  83. {
  84. return _lists.get(listId);
  85. }
  86. public L2RecipeList getRecipeByItemId(int itemId)
  87. {
  88. for (int i = 0; i < _lists.size(); i++)
  89. {
  90. L2RecipeList find = _lists.get(new Integer(i));
  91. if (find.getRecipeId() == itemId)
  92. {
  93. return find;
  94. }
  95. }
  96. return null;
  97. }
  98. public L2RecipeList getRecipeById(int recId)
  99. {
  100. for (int i = 0; i < _lists.size(); i++)
  101. {
  102. L2RecipeList find = _lists.get(new Integer(i));
  103. if (find.getId() == recId)
  104. {
  105. return find;
  106. }
  107. }
  108. return null;
  109. }
  110. public synchronized void requestBookOpen(L2PcInstance player, boolean isDwarvenCraft)
  111. {
  112. RecipeItemMaker maker = null;
  113. if (Config.ALT_GAME_CREATION) maker = _activeMakers.get(player);
  114. if (maker == null)
  115. {
  116. RecipeBookItemList response = new RecipeBookItemList(isDwarvenCraft, player.getMaxMp());
  117. response.addRecipes(isDwarvenCraft ? player.getDwarvenRecipeBook()
  118. : player.getCommonRecipeBook());
  119. player.sendPacket(response);
  120. return;
  121. }
  122. SystemMessage sm = new SystemMessage(SystemMessageId.CANT_ALTER_RECIPEBOOK_WHILE_CRAFTING);
  123. player.sendPacket(sm);
  124. return;
  125. }
  126. public synchronized void requestMakeItemAbort(L2PcInstance player)
  127. {
  128. _activeMakers.remove(player); // TODO: anything else here?
  129. }
  130. public synchronized void requestManufactureItem(L2PcInstance manufacturer, int recipeListId,
  131. L2PcInstance player)
  132. {
  133. L2RecipeList recipeList = getValidRecipeList(player, recipeListId);
  134. if (recipeList == null) return;
  135. List<L2RecipeList> dwarfRecipes = Arrays.asList(manufacturer.getDwarvenRecipeBook());
  136. List<L2RecipeList> commonRecipes = Arrays.asList(manufacturer.getCommonRecipeBook());
  137. if (!dwarfRecipes.contains(recipeList) && !commonRecipes.contains(recipeList))
  138. {
  139. Util.handleIllegalPlayerAction(player,"Warning!! Character "+player.getName()+" of account "+player.getAccountName()+" sent a false recipe id.",Config.DEFAULT_PUNISH);
  140. return;
  141. }
  142. RecipeItemMaker maker;
  143. if (Config.ALT_GAME_CREATION && (maker = _activeMakers.get(manufacturer)) != null) // check if busy
  144. {
  145. player.sendMessage("Manufacturer is busy, please try later.");
  146. return;
  147. }
  148. maker = new RecipeItemMaker(manufacturer, recipeList, player);
  149. if (maker._isValid)
  150. {
  151. if (Config.ALT_GAME_CREATION)
  152. {
  153. _activeMakers.put(manufacturer, maker);
  154. ThreadPoolManager.getInstance().scheduleGeneral(maker, 100);
  155. }
  156. else maker.run();
  157. }
  158. }
  159. public synchronized void requestMakeItem(L2PcInstance player, int recipeListId)
  160. {
  161. if (player.isInDuel())
  162. {
  163. player.sendPacket(new SystemMessage(SystemMessageId.CANT_CRAFT_DURING_COMBAT));
  164. return;
  165. }
  166. L2RecipeList recipeList = getValidRecipeList(player, recipeListId);
  167. if (recipeList == null) return;
  168. List<L2RecipeList> dwarfRecipes = Arrays.asList(player.getDwarvenRecipeBook());
  169. List<L2RecipeList> commonRecipes = Arrays.asList(player.getCommonRecipeBook());
  170. if (!dwarfRecipes.contains(recipeList) && !commonRecipes.contains(recipeList))
  171. {
  172. Util.handleIllegalPlayerAction(player,"Warning!! Character "+player.getName()+" of account "+player.getAccountName()+" sent a false recipe id.",Config.DEFAULT_PUNISH);
  173. return;
  174. }
  175. RecipeItemMaker maker;
  176. // check if already busy (possible in alt mode only)
  177. if (Config.ALT_GAME_CREATION && ((maker = _activeMakers.get(player)) != null))
  178. {
  179. SystemMessage sm = new SystemMessage(SystemMessageId.S1_S2);
  180. sm.addString("You are busy creating ");
  181. sm.addItemName(recipeList.getItemId());
  182. player.sendPacket(sm);
  183. return;
  184. }
  185. maker = new RecipeItemMaker(player, recipeList, player);
  186. if (maker._isValid)
  187. {
  188. if (Config.ALT_GAME_CREATION)
  189. {
  190. _activeMakers.put(player, maker);
  191. ThreadPoolManager.getInstance().scheduleGeneral(maker, 100);
  192. }
  193. else maker.run();
  194. }
  195. }
  196. //TODO XMLize the recipe list
  197. /*private void parseList(String line)
  198. {
  199. try
  200. {
  201. StringTokenizer st = new StringTokenizer(line, ";");
  202. List<L2RecipeInstance> recipePartList = new FastList<L2RecipeInstance>();
  203. //we use common/dwarf for easy reading of the recipes.csv file
  204. String recipeTypeString = st.nextToken();
  205. // now parse the string into a boolean
  206. boolean isDwarvenRecipe;
  207. if (recipeTypeString.equalsIgnoreCase("dwarven")) isDwarvenRecipe = true;
  208. else if (recipeTypeString.equalsIgnoreCase("common")) isDwarvenRecipe = false;
  209. else
  210. { //prints a helpfull message
  211. _log.warning("Error parsing recipes.csv, unknown recipe type " + recipeTypeString);
  212. return;
  213. }
  214. String recipeName = st.nextToken();
  215. int id = Integer.parseInt(st.nextToken());
  216. int recipeId = Integer.parseInt(st.nextToken());
  217. int level = Integer.parseInt(st.nextToken());
  218. //material
  219. StringTokenizer st2 = new StringTokenizer(st.nextToken(), "[],");
  220. while (st2.hasMoreTokens())
  221. {
  222. StringTokenizer st3 = new StringTokenizer(st2.nextToken(), "()");
  223. int rpItemId = Integer.parseInt(st3.nextToken());
  224. int quantity = Integer.parseInt(st3.nextToken());
  225. L2RecipeInstance rp = new L2RecipeInstance(rpItemId, quantity);
  226. recipePartList.add(rp);
  227. }
  228. int itemId = Integer.parseInt(st.nextToken());
  229. int count = Integer.parseInt(st.nextToken());
  230. //npc fee
  231. //String notdoneyet =
  232. st.nextToken();
  233. int mpCost = Integer.parseInt(st.nextToken());
  234. int successRate = Integer.parseInt(st.nextToken());
  235. L2RecipeList recipeList = new L2RecipeList(id, level, recipeId, recipeName, successRate,
  236. mpCost, itemId, count, isDwarvenRecipe);
  237. for (L2RecipeInstance recipePart : recipePartList)
  238. {
  239. recipeList.addRecipe(recipePart);
  240. }
  241. _lists.put(new Integer(_lists.size()), recipeList);
  242. }
  243. catch (Exception e)
  244. {
  245. _log.severe("Exception in RecipeController.parseList() - " + e);
  246. }
  247. }*/
  248. private void loadFromXML() throws SAXException, IOException, ParserConfigurationException
  249. {
  250. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  251. factory.setValidating(false);
  252. factory.setIgnoringComments(true);
  253. File file = new File(Config.DATAPACK_ROOT+"/data/"+RECIPES_FILE);
  254. if (file.exists())
  255. {
  256. Document doc = factory.newDocumentBuilder().parse(file);
  257. List<L2RecipeInstance> recipePartList = new FastList<L2RecipeInstance>();
  258. for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling())
  259. {
  260. if ("list".equalsIgnoreCase(n.getNodeName()))
  261. {
  262. String recipeName;
  263. int id;
  264. for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
  265. {
  266. if ("item".equalsIgnoreCase(d.getNodeName()))
  267. {
  268. recipePartList.clear();
  269. NamedNodeMap attrs = d.getAttributes();
  270. Node att;
  271. att = attrs.getNamedItem("id");
  272. if (att == null)
  273. {
  274. _log.severe("Missing id for recipe item, skipping");
  275. continue;
  276. }
  277. id = Integer.parseInt(att.getNodeValue());
  278. att = attrs.getNamedItem("name");
  279. if (att == null)
  280. {
  281. _log.severe("Missing name for recipe item id: "+id+", skipping");
  282. continue;
  283. }
  284. recipeName = att.getNodeValue();
  285. int recipeId = -1;
  286. int level = -1;
  287. boolean isDwarvenRecipe = true;
  288. int mpCost = -1;
  289. int successRate = -1;
  290. int prodId = -1;
  291. int count = -1;
  292. for (Node c = d.getFirstChild(); c != null; c = c.getNextSibling())
  293. {
  294. if ("recipe".equalsIgnoreCase(c.getNodeName()))
  295. {
  296. NamedNodeMap atts = c.getAttributes();
  297. recipeId = Integer.parseInt(atts.getNamedItem("id").getNodeValue());
  298. level = Integer.parseInt(atts.getNamedItem("level").getNodeValue());
  299. isDwarvenRecipe = atts.getNamedItem("type").getNodeValue().equalsIgnoreCase("dwarven");
  300. }
  301. else if ("mpCost".equalsIgnoreCase(c.getNodeName()))
  302. {
  303. mpCost = Integer.parseInt(c.getTextContent());
  304. }
  305. else if ("successRate".equalsIgnoreCase(c.getNodeName()))
  306. {
  307. successRate = Integer.parseInt(c.getTextContent());
  308. }
  309. else if ("ingredient".equalsIgnoreCase(c.getNodeName()))
  310. {
  311. int ingId = Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue());
  312. int ingCount = Integer.parseInt(c.getAttributes().getNamedItem("count").getNodeValue());
  313. recipePartList.add(new L2RecipeInstance(ingId, ingCount));
  314. }
  315. else if ("production".equalsIgnoreCase(c.getNodeName()))
  316. {
  317. prodId = Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue());
  318. count = Integer.parseInt(c.getAttributes().getNamedItem("count").getNodeValue());
  319. }
  320. }
  321. L2RecipeList recipeList = new L2RecipeList(id, level, recipeId, recipeName, successRate, mpCost, prodId, count, isDwarvenRecipe);
  322. for (L2RecipeInstance recipePart : recipePartList)
  323. {
  324. recipeList.addRecipe(recipePart);
  325. }
  326. _lists.put(_lists.size(), recipeList);
  327. }
  328. }
  329. }
  330. }
  331. }
  332. else
  333. {
  334. _log.severe("Recipes file ("+file.getAbsolutePath()+") doesnt exists.");
  335. }
  336. }
  337. private class RecipeItemMaker implements Runnable
  338. {
  339. protected boolean _isValid;
  340. protected List<TempItem> _items = null;
  341. protected final L2RecipeList _recipeList;
  342. protected final L2PcInstance _player; // "crafter"
  343. protected final L2PcInstance _target; // "customer"
  344. protected final L2Skill _skill;
  345. protected final int _skillId;
  346. protected final int _skillLevel;
  347. protected double _creationPasses;
  348. protected double _manaRequired;
  349. protected int _price;
  350. protected int _totalItems;
  351. protected int _materialsRefPrice;
  352. protected int _delay;
  353. public RecipeItemMaker(L2PcInstance pPlayer, L2RecipeList pRecipeList, L2PcInstance pTarget)
  354. {
  355. _player = pPlayer;
  356. _target = pTarget;
  357. _recipeList = pRecipeList;
  358. _isValid = false;
  359. _skillId = _recipeList.isDwarvenRecipe() ? L2Skill.SKILL_CREATE_DWARVEN
  360. : L2Skill.SKILL_CREATE_COMMON;
  361. _skillLevel = _player.getSkillLevel(_skillId);
  362. _skill = _player.getKnownSkill(_skillId);
  363. _player.isInCraftMode(true);
  364. if (_player.isAlikeDead())
  365. {
  366. _player.sendMessage("Dead people don't craft.");
  367. _player.sendPacket(ActionFailed.STATIC_PACKET);
  368. abort();
  369. return;
  370. }
  371. if (_target.isAlikeDead())
  372. {
  373. _target.sendMessage("Dead customers can't use manufacture.");
  374. _target.sendPacket(ActionFailed.STATIC_PACKET);
  375. abort();
  376. return;
  377. }
  378. if(_target.isProcessingTransaction())
  379. {
  380. _target.sendMessage("You are busy.");
  381. _target.sendPacket(ActionFailed.STATIC_PACKET);
  382. abort();
  383. return;
  384. }
  385. if(_player.isProcessingTransaction())
  386. {
  387. if(_player!=_target)
  388. {
  389. _target.sendMessage("Manufacturer "+_player.getName() + " is busy.");
  390. }
  391. _player.sendPacket(ActionFailed.STATIC_PACKET);
  392. abort();
  393. return;
  394. }
  395. // validate recipe list
  396. if ((_recipeList == null) || (_recipeList.getRecipes().length == 0))
  397. {
  398. _player.sendMessage("No such recipe");
  399. _player.sendPacket(ActionFailed.STATIC_PACKET);
  400. abort();
  401. return;
  402. }
  403. _manaRequired = _recipeList.getMpCost();
  404. // validate skill level
  405. if (_recipeList.getLevel() > _skillLevel)
  406. {
  407. _player.sendMessage("Need skill level " + _recipeList.getLevel());
  408. _player.sendPacket(ActionFailed.STATIC_PACKET);
  409. abort();
  410. return;
  411. }
  412. // check that customer can afford to pay for creation services
  413. if (_player != _target)
  414. {
  415. for (L2ManufactureItem temp : _player.getCreateList().getList())
  416. if (temp.getRecipeId() == _recipeList.getId()) // find recipe for item we want manufactured
  417. {
  418. _price = temp.getCost();
  419. if (_target.getAdena() < _price) // check price
  420. {
  421. _target.sendPacket(new SystemMessage(SystemMessageId.YOU_NOT_ENOUGH_ADENA));
  422. abort();
  423. return;
  424. }
  425. break;
  426. }
  427. }
  428. // make temporary items
  429. if ((_items = listItems(false)) == null)
  430. {
  431. abort();
  432. return;
  433. }
  434. // calculate reference price
  435. for (TempItem i : _items)
  436. {
  437. _materialsRefPrice += i.getReferencePrice() * i.getQuantity();
  438. _totalItems += i.getQuantity();
  439. }
  440. // initial mana check requires MP as written on recipe
  441. if (_player.getCurrentMp() < _manaRequired)
  442. {
  443. _target.sendPacket(new SystemMessage(SystemMessageId.NOT_ENOUGH_MP));
  444. abort();
  445. return;
  446. }
  447. // determine number of creation passes needed
  448. // can "equip" skillLevel items each pass
  449. _creationPasses = (_totalItems / _skillLevel) + ((_totalItems % _skillLevel)!=0 ? 1 : 0);
  450. if (Config.ALT_GAME_CREATION && _creationPasses != 0) // update mana required to "per pass"
  451. _manaRequired /= _creationPasses; // checks to validateMp() will only need portion of mp for one pass
  452. updateMakeInfo(true);
  453. updateCurMp();
  454. updateCurLoad();
  455. _player.isInCraftMode(false);
  456. _isValid = true;
  457. }
  458. public void run()
  459. {
  460. if (!Config.IS_CRAFTING_ENABLED)
  461. {
  462. _target.sendMessage("Item creation is currently disabled.");
  463. abort();
  464. return;
  465. }
  466. if (_player == null || _target == null)
  467. {
  468. _log.warning("player or target == null (disconnected?), aborting"+_target+_player);
  469. abort();
  470. return;
  471. }
  472. if (_player.isOnline()==0 || _target.isOnline()==0)
  473. {
  474. _log.warning("player or target is not online, aborting "+_target+_player);
  475. abort();
  476. return;
  477. }
  478. if (Config.ALT_GAME_CREATION && _activeMakers.get(_player) == null)
  479. {
  480. if (_target!=_player)
  481. {
  482. _target.sendMessage("Manufacture aborted");
  483. _player.sendMessage("Manufacture aborted");
  484. }
  485. else
  486. {
  487. _player.sendMessage("Item creation aborted");
  488. }
  489. abort();
  490. return;
  491. }
  492. if (Config.ALT_GAME_CREATION && !_items.isEmpty())
  493. {
  494. if (!validateMp()) return; // check mana
  495. _player.reduceCurrentMp(_manaRequired); // use some mp
  496. updateCurMp(); // update craft window mp bar
  497. grabSomeItems(); // grab (equip) some more items with a nice msg to player
  498. // if still not empty, schedule another pass
  499. if(!_items.isEmpty())
  500. {
  501. // divided by RATE_CONSUMABLES_COST to remove craft time increase on higher consumables rates
  502. _delay = (int) (Config.ALT_GAME_CREATION_SPEED * _player.getMReuseRate(_skill)
  503. * GameTimeController.TICKS_PER_SECOND / Config.RATE_CONSUMABLE_COST)
  504. * GameTimeController.MILLIS_IN_TICK;
  505. // FIXME: please fix this packet to show crafting animation (somebody)
  506. MagicSkillUse msk = new MagicSkillUse(_player, _skillId, _skillLevel, _delay, 0);
  507. _player.broadcastPacket(msk);
  508. _player.sendPacket(new SetupGauge(0, _delay));
  509. ThreadPoolManager.getInstance().scheduleGeneral(this, 100 + _delay);
  510. }
  511. else
  512. {
  513. // for alt mode, sleep delay msec before finishing
  514. _player.sendPacket(new SetupGauge(0, _delay));
  515. try {
  516. Thread.sleep(_delay);
  517. } catch (InterruptedException e) {
  518. } finally {
  519. finishCrafting();
  520. }
  521. }
  522. } // for old craft mode just finish
  523. else finishCrafting();
  524. }
  525. private void finishCrafting()
  526. {
  527. if(!Config.ALT_GAME_CREATION) _player.reduceCurrentMp(_manaRequired);
  528. // first take adena for manufacture
  529. if ((_target != _player) && _price > 0) // customer must pay for services
  530. {
  531. // attempt to pay for item
  532. L2ItemInstance adenatransfer = _target.transferItem("PayManufacture",
  533. _target.getInventory().getAdenaInstance().getObjectId(),
  534. _price, _player.getInventory(), _player);
  535. if(adenatransfer==null)
  536. {
  537. _target.sendPacket(new SystemMessage(SystemMessageId.YOU_NOT_ENOUGH_ADENA));
  538. abort();
  539. return;
  540. }
  541. }
  542. if ((_items = listItems(true)) == null) // this line actually takes materials from inventory
  543. { // handle possible cheaters here
  544. // (they click craft then try to get rid of items in order to get free craft)
  545. }
  546. else if (Rnd.get(100) < _recipeList.getSuccessRate())
  547. {
  548. rewardPlayer(); // and immediately puts created item in its place
  549. updateMakeInfo(true);
  550. }
  551. else
  552. {
  553. _player.sendMessage("Item(s) failed to create");
  554. if (_target != _player)
  555. _target.sendMessage("Item(s) failed to create");
  556. updateMakeInfo(false);
  557. }
  558. // update load and mana bar of craft window
  559. updateCurMp();
  560. updateCurLoad();
  561. _activeMakers.remove(_player);
  562. _player.isInCraftMode(false);
  563. _target.sendPacket(new ItemList(_target, false));
  564. }
  565. private void updateMakeInfo(boolean success)
  566. {
  567. if (_target == _player) _target.sendPacket(new RecipeItemMakeInfo(_recipeList.getId(), _target,
  568. success));
  569. else _target.sendPacket(new RecipeShopItemInfo(_player.getObjectId(), _recipeList.getId()));
  570. }
  571. private void updateCurLoad()
  572. {
  573. StatusUpdate su = new StatusUpdate(_target.getObjectId());
  574. su.addAttribute(StatusUpdate.CUR_LOAD, _target.getCurrentLoad());
  575. _target.sendPacket(su);
  576. }
  577. private void updateCurMp()
  578. {
  579. StatusUpdate su = new StatusUpdate(_target.getObjectId());
  580. su.addAttribute(StatusUpdate.CUR_MP, (int) _target.getCurrentMp());
  581. _target.sendPacket(su);
  582. }
  583. private void grabSomeItems()
  584. {
  585. int numItems = _skillLevel;
  586. while (numItems > 0 && !_items.isEmpty())
  587. {
  588. TempItem item = _items.get(0);
  589. int count = item.getQuantity();
  590. if (count >= numItems) count = numItems;
  591. item.setQuantity(item.getQuantity() - count);
  592. if (item.getQuantity() <= 0) _items.remove(0);
  593. else _items.set(0, item);
  594. numItems -= count;
  595. if (_target == _player)
  596. {
  597. SystemMessage sm = new SystemMessage(SystemMessageId.S1_S2_EQUIPPED); // you equipped ...
  598. sm.addNumber(count);
  599. sm.addItemName(item.getItemId());
  600. _player.sendPacket(sm);
  601. }
  602. else _target.sendMessage("Manufacturer " + _player.getName() + " used " + count + " "
  603. + item.getItemName());
  604. }
  605. }
  606. private boolean validateMp()
  607. {
  608. if (_player.getCurrentMp() < _manaRequired)
  609. {
  610. // rest (wait for MP)
  611. if (Config.ALT_GAME_CREATION)
  612. {
  613. _player.sendPacket(new SetupGauge(0, _delay));
  614. ThreadPoolManager.getInstance().scheduleGeneral(this, 100 + _delay);
  615. }
  616. else
  617. // no rest - report no mana
  618. {
  619. _target.sendPacket(new SystemMessage(SystemMessageId.NOT_ENOUGH_MP));
  620. abort();
  621. }
  622. return false;
  623. }
  624. return true;
  625. }
  626. private List<TempItem> listItems(boolean remove)
  627. {
  628. L2RecipeInstance[] recipes = _recipeList.getRecipes();
  629. Inventory inv = _target.getInventory();
  630. List<TempItem> materials = new FastList<TempItem>();
  631. for (L2RecipeInstance recipe : recipes)
  632. {
  633. int quantity = _recipeList.isConsumable() ? (int) (recipe.getQuantity() * Config.RATE_CONSUMABLE_COST)
  634. : (int) recipe.getQuantity();
  635. if (quantity > 0)
  636. {
  637. L2ItemInstance item = inv.getItemByItemId(recipe.getItemId());
  638. // check materials
  639. if (item==null || item.getCount() < quantity)
  640. {
  641. _target.sendMessage("You dont have the right elements for making this item"
  642. + ((_recipeList.isConsumable() && Config.RATE_CONSUMABLE_COST != 1) ? ".\nDue to server rates you need "
  643. + Config.RATE_CONSUMABLE_COST
  644. + "x more material than listed in recipe"
  645. : ""));
  646. abort();
  647. return null;
  648. }
  649. // make new temporary object, just for counting puroses
  650. TempItem temp = new TempItem(item, quantity);
  651. materials.add(temp);
  652. }
  653. }
  654. if (remove)
  655. {
  656. for(TempItem tmp : materials)
  657. {
  658. inv.destroyItemByItemId("Manufacture", tmp.getItemId(), tmp.getQuantity(), _target, _player);
  659. }
  660. }
  661. return materials;
  662. }
  663. private void abort()
  664. {
  665. updateMakeInfo(false);
  666. _player.isInCraftMode(false);
  667. _activeMakers.remove(_player);
  668. }
  669. /**
  670. * FIXME: This class should be in some other file, but I don't know where
  671. *
  672. * Class explanation:
  673. * For item counting or checking purposes. When you don't want to modify inventory
  674. * class contains itemId, quantity, ownerId, referencePrice, but not objectId
  675. */
  676. private class TempItem
  677. { // no object id stored, this will be only "list" of items with it's owner
  678. private int _itemId;
  679. private int _quantity;
  680. private int _ownerId;
  681. private int _referencePrice;
  682. private String _itemName;
  683. /**
  684. * @param item
  685. * @param quantity of that item
  686. */
  687. public TempItem(L2ItemInstance item, int quantity)
  688. {
  689. super();
  690. _itemId = item.getItemId();
  691. _quantity = quantity;
  692. _ownerId = item.getOwnerId();
  693. _itemName = item.getItem().getName();
  694. _referencePrice = item.getReferencePrice();
  695. }
  696. /**
  697. * @return Returns the quantity.
  698. */
  699. public int getQuantity()
  700. {
  701. return _quantity;
  702. }
  703. /**
  704. * @param quantity The quantity to set.
  705. */
  706. public void setQuantity(int quantity)
  707. {
  708. _quantity = quantity;
  709. }
  710. public int getReferencePrice()
  711. {
  712. return _referencePrice;
  713. }
  714. /**
  715. * @return Returns the itemId.
  716. */
  717. public int getItemId()
  718. {
  719. return _itemId;
  720. }
  721. /**
  722. * @return Returns the ownerId.
  723. */
  724. public int getOwnerId()
  725. {
  726. return _ownerId;
  727. }
  728. /**
  729. * @return Returns the itemName.
  730. */
  731. public String getItemName()
  732. {
  733. return _itemName;
  734. }
  735. }
  736. private void rewardPlayer()
  737. {
  738. int itemId = _recipeList.getItemId();
  739. int itemCount = _recipeList.getCount();
  740. L2ItemInstance createdItem = _target.getInventory().addItem("Manufacture", itemId, itemCount,
  741. _target, _player);
  742. // inform customer of earned item
  743. SystemMessage sm = null;
  744. if (itemCount > 1)
  745. {
  746. sm = new SystemMessage(SystemMessageId.EARNED_S2_S1_S);
  747. sm.addItemName(itemId);
  748. sm.addNumber(itemCount);
  749. _target.sendPacket(sm);
  750. } else
  751. {
  752. sm = new SystemMessage(SystemMessageId.EARNED_ITEM);
  753. sm.addItemName(itemId);
  754. _target.sendPacket(sm);
  755. }
  756. if (_target != _player)
  757. {
  758. // inform manufacturer of earned profit
  759. sm = new SystemMessage(SystemMessageId.EARNED_ADENA);
  760. sm.addNumber(_price);
  761. _player.sendPacket(sm);
  762. }
  763. if (Config.ALT_GAME_CREATION)
  764. {
  765. int recipeLevel = _recipeList.getLevel();
  766. int exp = createdItem.getReferencePrice() * itemCount;
  767. // one variation
  768. // exp -= materialsRefPrice; // mat. ref. price is not accurate so other method is better
  769. if (exp < 0) exp = 0;
  770. // another variation
  771. exp /= recipeLevel;
  772. for (int i = _skillLevel; i > recipeLevel; i--)
  773. exp /= 4;
  774. int sp = exp / 10;
  775. // Added multiplication of Creation speed with XP/SP gain
  776. // slower crafting -> more XP, faster crafting -> less XP
  777. // you can use ALT_GAME_CREATION_XP_RATE/SP to
  778. // modify XP/SP gained (default = 1)
  779. _player.addExpAndSp((int) _player.calcStat(Stats.EXPSP_RATE, exp * Config.ALT_GAME_CREATION_XP_RATE
  780. * Config.ALT_GAME_CREATION_SPEED, null, null)
  781. ,(int) _player.calcStat(Stats.EXPSP_RATE, sp * Config.ALT_GAME_CREATION_SP_RATE
  782. * Config.ALT_GAME_CREATION_SPEED, null, null));
  783. }
  784. updateMakeInfo(true); // success
  785. }
  786. }
  787. private L2RecipeList getValidRecipeList(L2PcInstance player, int id)
  788. {
  789. L2RecipeList recipeList = getRecipeList(id - 1);
  790. if ((recipeList == null) || (recipeList.getRecipes().length == 0))
  791. {
  792. player.sendMessage("No recipe for: " + id);
  793. player.isInCraftMode(false);
  794. return null;
  795. }
  796. return recipeList;
  797. }
  798. }