api.lua 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970
  1. -- File rewritten to be live-reloadable August 14, 2018 by MustTest.
  2. -- `mobs.registered' is checked throughout file, but only set `true' @ END!
  3. -- Localize functions.
  4. local pi = math.pi
  5. local square = math.sqrt
  6. local sin = math.sin
  7. local cos = math.cos
  8. local atan2 = math.atan2
  9. local abs = math.abs
  10. local min = math.min
  11. local max = math.max
  12. local ceil = math.ceil
  13. local floor = math.floor
  14. local random = math.random
  15. local v_round = vector.round
  16. local v_equals = vector.equals
  17. local v_distance = vector.distance
  18. local v_add = vector.add
  19. local rad = math.rad
  20. local deg = math.deg
  21. -- For debug reports.
  22. local function report(self, msg, range)
  23. if mobs.enable_reports then
  24. return
  25. end
  26. if self.name ~= mobs.report_name then
  27. return
  28. end
  29. local pname = gdac.name_of_admin
  30. if minetest.is_singleplayer() then
  31. pname = "singleplayer"
  32. end
  33. local player = minetest.get_player_by_name(pname)
  34. -- Range limit so I only get reports from mobs nearby.
  35. if player then
  36. local s = self.object:get_pos()
  37. local p = player:get_pos()
  38. if vector.distance(s, p) < (range or 50) then
  39. minetest.chat_send_player(pname, msg)
  40. end
  41. end
  42. end
  43. -- Export.
  44. mobs.report = report
  45. -- Function to tell mob which direction to turn to face target.
  46. -- Add pi to the returned yaw to face in the opposite direction.
  47. -- Fixed to use atan2 correctly by MustTest.
  48. local function yaw_to_pos(self, target, pos)
  49. local x = target.x - pos.x
  50. local z = target.z - pos.z
  51. local yaw = atan2(z, x) - self.rotate
  52. yaw = yaw - (pi / 2)
  53. return yaw
  54. end
  55. -- Function which takes a yaw value and "squares" it so it points in one of the
  56. -- 4 cardinal directions. Used to make mobs face along one of the horizontal
  57. -- axes, instead of diagonally, for some special situations.
  58. local function square_yaw(yaw)
  59. local pi2 = pi * 2
  60. if yaw < 0 then yaw = yaw + pi2 end
  61. if yaw > pi2 then yaw = yaw - pi2 end
  62. yaw = deg(yaw)
  63. if yaw <= 45 or yaw > 315 then
  64. yaw = 0 -- North.
  65. elseif yaw <= 315 and yaw > 225 then
  66. yaw = 270 -- East.
  67. elseif yaw <= 225 and yaw > 135 then
  68. yaw = 180 -- South.
  69. elseif yaw <= 135 and yaw > 45 then
  70. yaw = 90 -- West.
  71. end
  72. return rad(yaw)
  73. end
  74. -- Settings.
  75. local damage_enabled = true
  76. local peaceful_only = false
  77. local disable_blood = false
  78. local mobs_drop_items = minetest.settings:get_bool("mobs_drop_items") ~= false
  79. local mobs_griefing = true
  80. local creative = false
  81. local spawn_protected = minetest.settings:get_bool("mobs_spawn_protected") ~= false
  82. local remove_far = false
  83. local difficulty = tonumber(minetest.setting_get("mob_difficulty")) or 1.0
  84. local show_health = true
  85. local max_per_block = tonumber(minetest.settings:get("max_objects_per_block") or 99)
  86. local mob_chance_multiplier = tonumber(minetest.settings:get("mob_chance_multiplier") or 1)
  87. local default_knockback = 1
  88. -- Used by spawner function.
  89. mobs.spawn_protected = spawn_protected
  90. -- Legacy.
  91. if not mobs.invis then
  92. mobs.invis = {}
  93. end
  94. function mobs.is_invisible(self, pname)
  95. -- Administrative invisibility is paramount.
  96. if gdac_invis.is_invisible(pname) then
  97. return true
  98. end
  99. if self.ignore_invisibility then
  100. return
  101. end
  102. return cloaking.is_cloaked(pname)
  103. end
  104. -- creative check
  105. local creative_mode_cache = minetest.settings:get_bool("creative_mode")
  106. function mobs.is_creative(name)
  107. return creative_mode_cache or minetest.check_player_privs(name, {creative = true})
  108. end
  109. -- Peaceful mode message so players will know there are no monsters.
  110. -- Perform registration only ONCE.
  111. if not mobs.registered and peaceful_only then
  112. minetest.register_on_joinplayer(function(player)
  113. minetest.chat_send_player(player:get_player_name(),
  114. "# Server: Peaceful mode active - no new monsters will spawn.")
  115. end)
  116. end
  117. -- calculate aoc range for mob count
  118. local aoc_range = tonumber(minetest.settings:get("active_block_range")) * 16
  119. -- Pathfinding settings.
  120. local enable_pathfinding = true
  121. local stuck_timeout = 3
  122. -- Note: stuck path timeout is determined based on the length of the path, and
  123. -- is a mob-internal property [MustTest].
  124. -- Default nodes:
  125. local node_fire = "fire:basic_flame"
  126. local node_permanent_flame = "fire:permanent_flame"
  127. local node_ice = "default:ice"
  128. local node_snowblock = "default:snowblock"
  129. local node_snow = "default:snow"
  130. local node_pathfinder_place = "default:cobble"
  131. mobs.fallback_node = "default:cobble"
  132. -- play sound
  133. local function mob_sound(self, sound)
  134. if sound then
  135. local dist = self.sounds.distance or 20
  136. ambiance.sound_play(sound, self.object:get_pos(), 1.0, dist)
  137. -- This isn't working!
  138. --minetest.sound_play(sound, {
  139. -- object = self.object,
  140. -- gain = 1.0,
  141. -- max_hear_distance = self.sounds.distance
  142. --})
  143. end
  144. end
  145. local function set_state(self, newstate)
  146. local oldstate = self.state or ""
  147. if newstate ~= oldstate then
  148. local sm = mobs.state_machine
  149. if sm[oldstate] and sm[oldstate].exit then
  150. sm[oldstate].exit(self)
  151. end
  152. self.state = newstate
  153. self.substate = ""
  154. if sm[newstate] and sm[newstate].enter then
  155. sm[newstate].enter(self)
  156. end
  157. report(self, "stack: " .. self.state .. " (" .. self.substate .. ") -> " ..
  158. table.concat(self.state_stack or {}, ","))
  159. end
  160. end
  161. -- State transition function [MustTest]. Do not set mob state designation
  162. -- manually, call this function instead. It handles state transitions, etc.
  163. local function transition_state(self, newstate)
  164. self.state_stack = {}
  165. set_state(self, newstate)
  166. end
  167. -- Export.
  168. mobs.transition_state = function(...)
  169. transition_state(...)
  170. end
  171. -- States can have "substates". This is basically just an alternate main()
  172. -- function, so states can swap between different main() functions as needed.
  173. -- There are no exit() or enter() calls here.
  174. local function transition_substate(self, newsub)
  175. if newsub ~= self.substate then
  176. self.substate = newsub
  177. report(self, "stack: " .. self.state .. " (" .. self.substate .. ") -> " ..
  178. table.concat(self.state_stack or {}, ","))
  179. end
  180. end
  181. -- Export.
  182. mobs.transition_substate = function(...)
  183. transition_substate(...)
  184. end
  185. local function push_state(self, newstate)
  186. if not self.state_stack then
  187. self.state_stack = {}
  188. end
  189. if self.state and self.state ~= "" then
  190. table.insert(self.state_stack, 1, self.state)
  191. end
  192. set_state(self, newstate)
  193. end
  194. local function pop_state(self)
  195. if not self.state_stack then
  196. self.state_stack = {}
  197. end
  198. local state = self.state_stack[1]
  199. if state then
  200. table.remove(self.state_stack, 1)
  201. set_state(self, state)
  202. return
  203. end
  204. set_state(self, "")
  205. end
  206. local function do_attack(self, target)
  207. if self.state == "attack" then
  208. return
  209. end
  210. if target and target:get_pos() then
  211. self.attack = target
  212. transition_state(self, "attack")
  213. return
  214. else
  215. transition_state(self, "")
  216. return
  217. end
  218. end
  219. -- Check if the node at a position has 'walkable = true'.
  220. local function pos_walkable(pos)
  221. local nn = minetest.get_node(pos).name
  222. local dd = minetest.registered_nodes[nn]
  223. return dd.walkable
  224. end
  225. local function set_velocity(self, v)
  226. local yaw = (self.object:get_yaw() or 0) + (self.rotate or 0)
  227. local vel = self.object:get_velocity()
  228. local y = 0
  229. if vel then
  230. y = vel.y or 0
  231. end
  232. -- Fix crash: 2020-09-12 14:26:15: ERROR[Main]: ServerError: AsyncErr:
  233. -- ServerThread::run Lua: Runtime error from mod 'griefer' in callback
  234. -- luaentity_Step(): Invalid float vector dimension range 'y' (expected
  235. -- -2.14748e+06 < y < 2.14748e+06 got -1.96364e+12).
  236. y = max(min(y, 200), -200)
  237. self.object:set_velocity({
  238. x = sin(yaw) * -v,
  239. y = y,
  240. z = cos(yaw) * v
  241. })
  242. -- Store the requested velocity.
  243. local o = self.wanted_velocity or 0
  244. self.wanted_velocity = v
  245. if v <= 0 and o > 0 then
  246. self.stand_timer = 0
  247. end
  248. if v <= 0 then
  249. self.stuck_timer = 0
  250. end
  251. end
  252. local function get_velocity(self)
  253. local v = self.object:get_velocity()
  254. return ((v.x * v.x) + (v.z * v.z)) ^ 0.5
  255. end
  256. -- set and return valid yaw
  257. local function set_yaw(self, yaw, delay)
  258. if not yaw or yaw ~= yaw then
  259. yaw = 0
  260. end
  261. delay = delay or 0
  262. if delay == 0 then
  263. self.object:set_yaw(yaw)
  264. return yaw
  265. end
  266. self.target_yaw = yaw
  267. self.delay = delay
  268. return self.target_yaw
  269. end
  270. -- global function to set mob yaw
  271. function mobs.yaw(self, yaw, delay)
  272. set_yaw(self, yaw, delay)
  273. end
  274. local function set_animation(self, anim, speed)
  275. if not self.animation or not anim then
  276. return
  277. end
  278. self.animation.current = self.animation.current or ""
  279. -- only set different animation for attacks when setting to same set
  280. if anim ~= "punch" and anim ~= "shoot"
  281. and string.find(self.animation.current, anim) then
  282. return
  283. end
  284. -- check for more than one animation
  285. local num = 0
  286. for n = 1, 4 do
  287. if self.animation[anim .. n .. "_start"]
  288. and self.animation[anim .. n .. "_end"] then
  289. num = n
  290. end
  291. end
  292. -- choose random animation from set
  293. if num > 0 then
  294. num = random(0, num)
  295. anim = anim .. (num ~= 0 and num or "")
  296. end
  297. if anim == self.animation.current
  298. or not self.animation[anim .. "_start"]
  299. or not self.animation[anim .. "_end"] then
  300. return
  301. end
  302. self.animation.current = anim
  303. local anim_speed = (speed or
  304. self.animation[anim .. "_speed"] or
  305. self.animation.speed_normal or 15)
  306. self.object:set_animation({
  307. x = self.animation[anim .. "_start"],
  308. y = self.animation[anim .. "_end"]},
  309. anim_speed,
  310. 0, self.animation[anim .. "_loop"] ~= false)
  311. end
  312. -- Above function exported for "mount.lua".
  313. function mobs.set_animation(self, anim)
  314. set_animation(self, anim)
  315. end
  316. -- Calculate distance.
  317. local function get_distance(a, b)
  318. local x, y, z = a.x - b.x, a.y - b.y, a.z - b.z
  319. return square(x * x + y * y + z * z)
  320. end
  321. -- Check line of sight using raycasting (thanks Astrobe).
  322. local function raycast_los(self, pos1, pos2)
  323. local ray = minetest.raycast(pos1, pos2, false, true)
  324. local thing = ray:next()
  325. while thing do
  326. if thing.type == "node" then
  327. local name = minetest.get_node(thing.under).name
  328. local ndef = minetest.registered_nodes[name]
  329. if ndef and ndef.walkable then
  330. return false
  331. end
  332. end
  333. thing = ray:next()
  334. end
  335. return true
  336. end
  337. -- Export.
  338. function mobs.line_of_sight(self, pos1, pos2)
  339. return raycast_los(self, pos1, pos2)
  340. end
  341. -- Are we flying in what we are suppose to? (taikedz)
  342. local function flight_check(self, pos_w)
  343. if type(self.fly_in) == "string" and self.standing_in == self.fly_in then
  344. return true
  345. elseif type(self.fly_in) == "table" then
  346. for _, fly_in in ipairs(self.fly_in) do
  347. if self.standing_in == fly_in then
  348. return true
  349. end
  350. end
  351. end
  352. local def = minetest.reg_ns_nodes[self.standing_in]
  353. if not def then return false end -- nil check
  354. -- stops mobs getting stuck inside stairs and plantlike nodes
  355. if def.drawtype ~= "airlike"
  356. and def.drawtype ~= "liquid"
  357. and def.drawtype ~= "flowingliquid" then
  358. return true
  359. end
  360. -- Enables mobs to fly in non-walkable stuff like thin "default:snow".
  361. if not def.walkable then
  362. return true
  363. end
  364. return false
  365. end
  366. -- custom particle effects
  367. local function effect(
  368. pos, amount, texture, min_size, max_size, radius, gravity, glow, fall)
  369. radius = radius or 2
  370. min_size = min_size or 0.5
  371. max_size = max_size or 1
  372. gravity = gravity or -10
  373. glow = glow or 0
  374. if fall == true then
  375. fall = 0
  376. elseif fall == false then
  377. fall = radius
  378. else
  379. fall = -radius
  380. end
  381. minetest.add_particlespawner({
  382. amount = amount,
  383. time = 0.25,
  384. minpos = pos,
  385. maxpos = pos,
  386. minvel = {x = -radius, y = fall, z = -radius},
  387. maxvel = {x = radius, y = radius, z = radius},
  388. minacc = {x = 0, y = gravity, z = 0},
  389. maxacc = {x = 0, y = gravity, z = 0},
  390. minexptime = 0.1,
  391. maxexptime = 1,
  392. minsize = min_size,
  393. maxsize = max_size,
  394. texture = texture,
  395. glow = glow,
  396. })
  397. end
  398. -- Update nametag colour.
  399. local function update_tag(self)
  400. local col = "#00FF00"
  401. local qua = self.hp_max / 4
  402. if self.health <= floor(qua * 3) then
  403. col = "#FFFF00"
  404. end
  405. if self.health <= floor(qua * 2) then
  406. col = "#FF6600"
  407. end
  408. if self.health <= floor(qua) then
  409. col = "#FF0000"
  410. end
  411. self.object:set_properties({
  412. nametag = self.nametag,
  413. nametag_color = col,
  414. })
  415. end
  416. -- drop items
  417. local function item_drop(self, cooked)
  418. -- check for nil or no drops
  419. if not self.drops or #self.drops == 0 then
  420. return
  421. end
  422. -- no drops if disabled by setting
  423. if not mobs_drop_items then return end
  424. -- no drops for child mobs
  425. if self.child then return end
  426. local obj, item, num
  427. local pos = self.object:get_pos()
  428. for n = 1, #self.drops do
  429. if random(1, self.drops[n].chance) == 1 then
  430. num = random(self.drops[n].min or 0, self.drops[n].max or 1)
  431. item = self.drops[n].name
  432. -- cook items when true
  433. if cooked then
  434. local output = minetest.get_craft_result({
  435. method = "cooking", width = 1, items = {item}})
  436. if output and output.item and not output.item:is_empty() then
  437. item = output.item:get_name()
  438. end
  439. end
  440. -- add item if it exists
  441. obj = minetest.add_item(pos, ItemStack(item .. " " .. num))
  442. if obj and obj:get_luaentity() then
  443. obj:set_velocity({
  444. x = random(-10, 10) / 9,
  445. y = 6,
  446. z = random(-10, 10) / 9,
  447. })
  448. elseif obj then
  449. obj:remove() -- item does not exist
  450. end
  451. end
  452. end
  453. self.drops = {}
  454. end
  455. -- check if mob is dead or only hurt
  456. local function check_for_death(self, cause, cmi_cause)
  457. -- has health actually changed?
  458. if self.health == self.old_health and self.health > 0 then
  459. return
  460. end
  461. self.old_health = self.health
  462. -- still got some health? play hurt sound
  463. if self.health > 0 then
  464. mob_sound(self, self.sounds.damage)
  465. -- make sure health isn't higher than max
  466. if self.health > self.hp_max then
  467. self.health = self.hp_max
  468. end
  469. -- backup nametag so we can show health stats
  470. if not self.nametag2 then
  471. self.nametag2 = self.nametag or ""
  472. end
  473. if show_health and self.show_health ~= false and
  474. (cmi_cause and cmi_cause.type == "punch") then
  475. self.htimer = 2
  476. self.nametag = "♥ " .. self.health .. " / " .. self.hp_max
  477. update_tag(self)
  478. end
  479. return false
  480. end
  481. -- Mob will die, check if we were attacked.
  482. if cause == "hit" then
  483. if self.last_attacked_by and self.last_attacked_by ~= "" then
  484. local attacked_by = minetest.get_player_by_name(self.last_attacked_by)
  485. if attacked_by then
  486. mobs.player_killed_mob(self, attacked_by)
  487. end
  488. end
  489. end
  490. -- only drop items if weapon is of sufficient level to overcome mob's armor level
  491. local can_drop = true
  492. if cmi_cause and cmi_cause.tool_capabilities then
  493. local max_drop_level = (cmi_cause.tool_capabilities.max_drop_level or 0)
  494. -- Increase weapon's max drop level if rank is level 7.
  495. local tool_level = 1
  496. if cmi_cause.wielded then
  497. local tool_meta = cmi_cause.wielded:get_meta()
  498. tool_level = tonumber(tool_meta:get_string("tr_lastlevel")) or 1
  499. end
  500. if tool_level >= 7 then
  501. max_drop_level = max_drop_level + 1
  502. end
  503. if (max_drop_level) < (self.armor_level or 0) then
  504. can_drop = false
  505. end
  506. end
  507. -- mob doesn't drop anything if killed by sunlight
  508. -- this fixes the problem of drops being scattered around after sunrise
  509. -- caused by icemen and sandmen
  510. if cause == "light" then
  511. can_drop = false
  512. end
  513. if can_drop then
  514. -- dropped cooked item if mob died in lava
  515. if cause == "lava" or cause == "fire" then
  516. item_drop(self, true)
  517. else
  518. item_drop(self, nil)
  519. end
  520. end
  521. mob_sound(self, self.sounds.death)
  522. local pos = self.object:get_pos()
  523. -- execute custom death function
  524. if self.on_die then
  525. self.on_die(self, pos)
  526. -- Mark for removal as last action on mob_step().
  527. self.mkrm = true
  528. return true
  529. end
  530. -- default death function and die animation (if defined)
  531. if self.animation
  532. and self.animation.die_start
  533. and self.animation.die_end then
  534. local frames = self.animation.die_end - self.animation.die_start
  535. local speed = self.animation.die_speed or 15
  536. local length = max(frames / speed, 0)
  537. self.attack = nil
  538. self.v_start = false
  539. self.blinktimer = 0
  540. self.passive = true
  541. transition_state(self, "die")
  542. set_velocity(self, 0)
  543. set_animation(self, "die")
  544. minetest.after(length, function(self)
  545. -- Mark for removal as last action on mob_step().
  546. -- Note: this is deferred for a bit!
  547. self.mkrm = true
  548. end, self)
  549. else
  550. -- Mark for removal as last action on mob_step().
  551. self.mkrm = true
  552. end
  553. effect(pos, 20, "tnt_smoke.png")
  554. return true
  555. end
  556. -- Check if within physical map limits (-30911 to 30927).
  557. local function within_limits(pos, radius)
  558. if (pos.x - radius) > -30913
  559. and (pos.x + radius) < 30928
  560. and (pos.y - radius) > -30913
  561. and (pos.y + radius) < 30928
  562. and (pos.z - radius) > -30913
  563. and (pos.z + radius) < 30928 then
  564. return true -- Within limits.
  565. end
  566. return false -- Beyond limits.
  567. end
  568. -- Returns true if node can deal damage to self.
  569. local function is_node_dangerous(self, nodename, ndef)
  570. if nodename == "air" then
  571. return false
  572. end
  573. if not ndef then
  574. ndef = minetest.registered_nodes[nodename]
  575. end
  576. if not ndef then
  577. return true
  578. end
  579. local groups = ndef.groups
  580. local water = groups.water or 0
  581. local lava = groups.lava or 0
  582. local fire = groups.fire or 0
  583. if (self.water_damage or 0) > 0 and water ~= 0 then
  584. return true
  585. end
  586. if (self.lava_damage or 0) > 0 and lava ~= 0 then
  587. return true
  588. end
  589. if (self.fire_damage or 0) > 0 and fire ~= 0 then
  590. return true
  591. end
  592. if ndef.damage_per_second > 0 then
  593. return true
  594. end
  595. return false
  596. end
  597. -- Get node but use fallback for nil or unknown.
  598. local function node_ok(pos, fallback)
  599. fallback = fallback or mobs.fallback_node
  600. local node = minetest.get_node_or_nil(pos)
  601. if node and minetest.registered_nodes[node.name] then
  602. return node
  603. end
  604. return minetest.registered_nodes[fallback]
  605. end
  606. -- This function moves a mob to the center of the X,Z column.
  607. -- True is returned to indicate the mob is moving; otherwise false.
  608. -- Note: the point is to get the mob's collision box entirely inside the X,Z
  609. -- plain of the node it is standing on; if this can't be achieved, the
  610. -- pathfinder WILL exhibit bugs!
  611. local function keep_mob_centered(self, ss)
  612. local s = ss or self.object:get_pos()
  613. local c = vector.round(s)
  614. -- Have mob position himself nearer the center of the node.
  615. if abs(s.x - c.x) > 0.2 or abs(s.z - c.z) > 0.2 then
  616. set_yaw(self, yaw_to_pos(self, c, s))
  617. set_velocity(self, 0.2)
  618. set_animation(self, "walk", 5)
  619. return true
  620. end
  621. end
  622. -- This function causes a mob to walk slowly toward its facing direction until
  623. -- it detects an obstacle (of any kind). It returns true to indicate the mob is
  624. -- moving.
  625. local function walk_mob_forward(self)
  626. -- Function is not defined yet.
  627. if not mobs.facing_wall_or_pit(self) then
  628. set_velocity(self, 0.5)
  629. set_animation(self, "walk", 5)
  630. return true
  631. end
  632. end
  633. local function show_position(p)
  634. -- Keep this particle code for debugging purposes [MustTest].
  635. -- Spawn particle at actual computed position without rounding.
  636. local pname = "singleplayer"
  637. if not minetest.is_singleplayer() then
  638. pname = gdac.name_of_admin
  639. end
  640. utility.original_add_particle({
  641. playername = pname,
  642. pos = p,
  643. velocity = {x=0, y=0, z=0},
  644. acceleration = {x=0, y=0, z=0},
  645. expirationtime = 0.5,
  646. size = 1,
  647. collisiondetection = false,
  648. vertical = false,
  649. texture = "bubble.png",
  650. })
  651. end
  652. -- This function computes the rounded position of the node in front of the mob.
  653. -- The math must be such that the mob MUST be standing WITHIN the node's X,Z
  654. -- bounds, in order to get the position of the node ahead. If this is not the
  655. -- case, then the mob would detect obstacles either too soon or too late to
  656. -- correctly deal with them.
  657. local function get_ahead_pos(self, pos, yaw)
  658. -- Copy position argument so we do not modify it.
  659. local s = (pos and vector.copy(pos)) or self.object:get_pos()
  660. s.y = s.y + self.collisionbox[2] + 0.5
  661. local off = (pi / 2)
  662. local cir = (pi * 2)
  663. local dir = yaw or (self.object:get_yaw() + off)
  664. -- Adjustment factor to improve accuracy.
  665. local fac = 0.99
  666. local ang = dir - off
  667. if ang < 0 then ang = ang + cir end
  668. if ang > cir then ang = ang - cir end
  669. local dd = deg(ang)
  670. --report(self, "angle: " .. dd)
  671. -- Increase distance when facing corners.
  672. if dd > 30 and dd < 60 then
  673. fac = 1.3
  674. elseif dd > 120 and dd < 150 then
  675. fac = 1.3
  676. elseif dd > 210 and dd < 240 then
  677. fac = 1.3
  678. elseif dd > 300 and dd < 330 then
  679. fac = 1.3
  680. end
  681. local p = {
  682. x = s.x + (cos(dir) * fac),
  683. y = s.y,
  684. z = s.z + (sin(dir) * fac),
  685. }
  686. -- Keep this particle code for debugging purposes [MustTest].
  687. --[[
  688. -- Spawn particle at actual computed position without rounding.
  689. local pname = "singleplayer"
  690. if not minetest.is_singleplayer() then
  691. pname = gdac.name_of_admin
  692. end
  693. utility.original_add_particle({
  694. playername = pname,
  695. pos = p,
  696. velocity = {x=0, y=0, z=0},
  697. acceleration = {x=0, y=0, z=0},
  698. expirationtime = 0.5,
  699. size = 1,
  700. collisiondetection = false,
  701. vertical = false,
  702. texture = "bubble.png",
  703. })
  704. --]]
  705. p = v_round(p)
  706. --[[
  707. -- Spawn particle at rounded node position.
  708. utility.original_add_particle({
  709. playername = pname,
  710. pos = p,
  711. velocity = {x=0, y=0, z=0},
  712. acceleration = {x=0, y=0, z=0},
  713. expirationtime = 0.5,
  714. size = 4,
  715. collisiondetection = false,
  716. vertical = false,
  717. texture = "bubble.png",
  718. })
  719. --]]
  720. return p
  721. end
  722. -- This function returns a list of walkable surfaces which are level with the
  723. -- position. The returned list contains positions *above* the walkable surfaces.
  724. -- The center position is also included, for a max total of 9 locations.
  725. local function walkable_around(pos)
  726. local minp = v_add(pos, {x=-1, y=0, z=-1})
  727. local maxp = v_add(pos, {x=1, y=0, z=1})
  728. return hb4.find_walkable_in_area_under_unwalkable(minp, maxp)
  729. end
  730. -- Check if a position is a wall or pit. You should pass the rounded position of
  731. -- the node which the mob wants to move INTO. Always returns two values,
  732. -- true/false, and a reason string.
  733. local function is_wall_or_pit(self, wp)
  734. local drop = (self.fear_height or 0)
  735. local jump = (self.jump_height or 0)
  736. -- Note: we need to add 1 to the jump height in order to take care of the case
  737. -- that the wall has a hole in it near the top. The mob would not be able to
  738. -- jump through such a wall because of the block above (assuming the mob is 2
  739. -- blocks high).
  740. jump = jump + 1
  741. -- Start the raycast from the top and go down.
  742. -- Note: the raycast ignores air nodes. So we do not need to do air checks.
  743. -- Note: the raycast returns ALL nodes, not just those exposed to air.
  744. local p1 = v_add(wp, {x=0, y=jump, z=0})
  745. local p2 = v_add(wp, {x=0, y=-drop, z=0})
  746. local ray = minetest.raycast(p1, p2, false, true)
  747. local thing = ray:next()
  748. local head_solid = false
  749. while thing do
  750. if thing.type == "node" then
  751. local p = thing.under
  752. local n = minetest.get_node(p).name
  753. local d = minetest.registered_nodes[n]
  754. if not d then
  755. return true, "undef"
  756. end
  757. if is_node_dangerous(self, n, d) then
  758. if head_solid then
  759. return true, "wall"
  760. else
  761. return true, "danger"
  762. end
  763. end
  764. -- If the node is not walkable, skip these checks.
  765. if d.walkable then
  766. if p.y == p1.y then
  767. head_solid = true
  768. elseif p.y == (p1.y - 1) then
  769. return true, "wall"
  770. elseif p.y == (p1.y - 2) and head_solid then
  771. return true, "wall"
  772. else
  773. return false, "surface"
  774. end
  775. end
  776. end
  777. thing = ray:next()
  778. end
  779. -- If we reach here, the raycast did not intersect any nodes.
  780. if (self.fear_height or 0) == 0 then
  781. return false, "nofear"
  782. end
  783. return true, "pit"
  784. end
  785. -- Export function.
  786. mobs.is_wall_or_pit = is_wall_or_pit
  787. -- Is mob facing a wall or a pit/cliff. Always returns two values, true/false,
  788. -- and a reason string.
  789. local function facing_wall_or_pit(self)
  790. if self.driver then
  791. return false, "driver"
  792. end
  793. local ahead = get_ahead_pos(self)
  794. return is_wall_or_pit(self, ahead)
  795. end
  796. -- Export function.
  797. mobs.facing_wall_or_pit = facing_wall_or_pit
  798. -- This function is to be called by the pathfinder to determine if a waypoint
  799. -- would be dangerous for a mob to follow. Note that the pathfinder does not
  800. -- place waypoints over deep pits, cliffs, or walls, so we do not need to check
  801. -- for that kind of blockage. Note: pathfinder returns rounded positions.
  802. function waypoint_dangerous(self, waypoint)
  803. local bnode = node_ok(waypoint)
  804. -- Is waypoint inside a dangerous node?
  805. if is_node_dangerous(self, bnode.name) then
  806. return true
  807. end
  808. end
  809. -- Global function.
  810. function mobs.node_ok(pos, fallback)
  811. return node_ok(pos, fallback)
  812. end
  813. -- Get list of players and mobs in radius. Note: all "actor" (player, mob) type
  814. -- targets are returned, irrespective of invisibility. Self is never included.
  815. local function get_targets_in_radius(self, pos, radius)
  816. local list = {}
  817. local objs = minetest.get_objects_inside_radius(pos, radius)
  818. for k, v in ipairs(objs) do
  819. if v:is_player() then
  820. list[#list + 1] = v
  821. else
  822. local ent = v:get_luaentity()
  823. if ent and (ent.mob or ent._cmi_is_mob) then
  824. if ent.object ~= self.object then
  825. list[#list + 1] = v
  826. end
  827. end
  828. end
  829. end
  830. return list
  831. end
  832. -- Environmental damage (water, lava, fire, light).
  833. local function do_env_damage(self)
  834. -- feed/tame text timer (so mob 'full' messages dont spam chat)
  835. if self.htimer > 0 then
  836. self.htimer = self.htimer - 1
  837. end
  838. -- reset nametag after showing health stats
  839. if self.htimer < 1 and self.nametag2 then
  840. self.nametag = self.nametag2
  841. self.nametag2 = nil
  842. update_tag(self)
  843. end
  844. local pos = self.object:get_pos()
  845. self.time_of_day = minetest.get_timeofday()
  846. -- remove mob if beyond map limits
  847. if not within_limits(pos, 0) then
  848. -- Mark for removal as last action on mob_step().
  849. self.mkrm = true
  850. return
  851. end
  852. -- mob may simply despawn at daytime, without dropping anything
  853. if random(1, 10) == 1 then -- add some random delay chance
  854. if self.daytime_despawn and pos.y > -10
  855. and self.time_of_day > 0.2
  856. and self.time_of_day < 0.8
  857. and (minetest.get_node_light(pos) or 0) > 12 then
  858. if self.on_despawn then
  859. self.on_despawn(self)
  860. return
  861. else
  862. -- Mark for removal as last action on mob_step().
  863. self.mkrm = true
  864. return
  865. end
  866. end
  867. end
  868. -- bright light harms mob
  869. -- daylight above ground
  870. if self.light_damage ~= 0
  871. and pos.y > -10
  872. and self.time_of_day > 0.2
  873. and self.time_of_day < 0.8
  874. and (minetest.get_node_light(pos) or 0) > 12 then
  875. self.health = self.health - self.light_damage
  876. effect(pos, 5, "tnt_smoke.png")
  877. if check_for_death(self, "light", {type = "light"}) then return end
  878. end
  879. if self.despawns_in_dark_caves and pos.y < -12 then
  880. if (minetest.get_node_light(pos) or 0) == 0 then
  881. -- Mark for removal as last action on mob_step().
  882. self.mkrm = true
  883. return
  884. end
  885. end
  886. -- don't fall when on ignore, just stand still
  887. if self.standing_in == "ignore" then
  888. self.object:set_velocity({x = 0, y = 0, z = 0})
  889. end
  890. local nodef = minetest.reg_ns_nodes[self.standing_in]
  891. local nodef2 = minetest.reg_ns_nodes[self.standing_on]
  892. -- Stairs nodes don't do env damage.
  893. if not nodef or not nodef2 then
  894. return
  895. end
  896. pos.y = pos.y + 1 -- for particle effect position
  897. -- water
  898. if self.water_damage ~= 0 and nodef.groups.water then
  899. if self.water_damage ~= 0 then
  900. self.health = self.health - self.water_damage
  901. effect(pos, 5, "bubble.png", nil, nil, 1, nil)
  902. if check_for_death(self, "water", {type = "environment",
  903. pos = pos, node = self.standing_in}) then return end
  904. end
  905. -- lava damage
  906. elseif self.lava_damage ~= 0 and nodef.groups.lava then
  907. if self.lava_damage ~= 0 then
  908. self.health = self.health - self.lava_damage
  909. effect(pos, 5, "fire_basic_flame.png", nil, nil, 1, nil)
  910. if check_for_death(self, "lava", {type = "environment",
  911. pos = pos, node = self.standing_in}) then return end
  912. end
  913. -- fire damage
  914. elseif self.fire_damage ~= 0 and nodef.groups.fire then
  915. self.health = self.health - self.fire_damage
  916. effect(pos, 15, "fire_basic_flame.png", 1, 5, 1, 0.2, 15, true)
  917. if check_for_death(self, "fire", {type = "environment", pos = pos,
  918. node = self.standing_in, hot = true}) then return end
  919. -- damage_per_second node check
  920. elseif nodef.damage_per_second ~= 0
  921. and nodef.groups.lava == nil and nodef.groups.fire == nil then
  922. self.health = self.health - nodef.damage_per_second
  923. effect(pos, 5, "tnt_smoke.png")
  924. if check_for_death(self, "dps", {type = "environment",
  925. pos = pos, node = self.standing_in}) then return end
  926. end
  927. if nodef2.groups.lava and self.lava_annihilates and self.lava_annihilates == true then
  928. self.health = 0
  929. effect(pos, 5, "tnt_smoke.png")
  930. pos.y = pos.y - 1 -- erase effect of adjusting for particle position.
  931. local pb = v_round(pos) -- use rounded position
  932. local pa = {x=pb.x, y=pb.y+1, z=pb.z}
  933. if minetest.get_node(pb).name == "air" and minetest.get_node(pa).name == "air" then
  934. if self.makes_bones_in_lava and self.makes_bones_in_lava == true then
  935. minetest.add_node(pb, {name="bones:bones_type2"})
  936. local meta = minetest.get_meta(pb)
  937. meta:set_int("protection_cancel", 1)
  938. minetest.add_node(pa, {name="fire:basic_flame"})
  939. minetest.check_for_falling(pb)
  940. else
  941. minetest.add_node(pb, {name="fire:basic_flame"})
  942. end
  943. end
  944. if check_for_death(self, "lava", {type = "environment",
  945. pos = pos, node = self.standing_in}) then return end
  946. end
  947. check_for_death(self, "", {type = "unknown"})
  948. end
  949. -- Arrow shooting code extracted into its own function [MustTest].
  950. local function shoot_arrow(self, vec)
  951. -- Play shoot attack sound.
  952. mob_sound(self, self.sounds.shoot_attack)
  953. -- Spawn arrow comming from mid-height of mob.
  954. local p = self.object:get_pos()
  955. p.y = p.y + (self.collisionbox[2] + self.collisionbox[5]) / 2
  956. if minetest.registered_entities[self.arrow] then
  957. local obj = minetest.add_entity(p, self.arrow)
  958. if not obj then return end -- Sanity check.
  959. local ent = obj:get_luaentity()
  960. if not ent then
  961. obj:remove()
  962. return
  963. end -- Sanity check.
  964. local amount = (vec.x * vec.x + vec.y * vec.y + vec.z * vec.z) ^ 0.5
  965. local v = ent.velocity or 1 -- or set to default
  966. ent.switch = 1
  967. ent.owner_obj = self.object -- Add unique owner object ref to arrow.
  968. -- Offset makes shoot aim accurate.
  969. vec.y = vec.y + self.shoot_offset
  970. vec.x = vec.x * (v / amount)
  971. vec.y = vec.y * (v / amount)
  972. vec.z = vec.z * (v / amount)
  973. obj:set_velocity(vec)
  974. end
  975. end
  976. -- Export.
  977. mobs.shoot_arrow = function(...)
  978. shoot_arrow(...)
  979. end
  980. -- Target punching code extracted into its own function [MustTest].
  981. local function punch_target(self, dtime)
  982. if not self.attack then return end
  983. if not self.attack:get_pos() then return end
  984. -- If the punch timer is still running since the last successful punch, then
  985. -- don't do anything.
  986. if (self.punch_timer or 0) > 0 then return end
  987. local s2 = self.object:get_pos()
  988. local p2 = self.attack:get_pos()
  989. p2.y = p2.y + 0.5
  990. s2.y = s2.y + 0.5
  991. if not raycast_los(self, p2, s2) then
  992. return
  993. end
  994. -- play attack sound
  995. mob_sound(self, self.sounds.attack)
  996. local targetname = (self.attack:is_player() and self.attack:get_player_name() or "")
  997. -- punch player (or what player is attached to)
  998. local attached = self.attack:get_attach()
  999. if attached or default.player_attached[targetname] then
  1000. -- Mob has a chance of removing the player from whatever they're attached to.
  1001. -- This chance only applies on the mob's first hit; if they fail to detach
  1002. -- the player, the mob's target is set to the entity the player is attached to.
  1003. if self.attack:is_player() and random(1, 5) == 1 then
  1004. utility.detach_player_with_message(self.attack)
  1005. elseif attached then
  1006. self.attack = attached
  1007. end
  1008. end
  1009. -- If attacking an entity that has no attached player, then stop attacking.
  1010. if targetname == "" then
  1011. local luaent = self.attack:get_luaentity()
  1012. if luaent and not luaent._cmi_is_mob then
  1013. local children = self.attack:get_children()
  1014. if not children or #children == 0 then
  1015. self.attack = nil
  1016. return
  1017. else
  1018. local has_player = false
  1019. for k, v in ipairs(children) do
  1020. if v:is_player() then
  1021. has_player = true
  1022. end
  1023. end
  1024. if not has_player then
  1025. self.attack = nil
  1026. return
  1027. end
  1028. end
  1029. end
  1030. end
  1031. -- Don't bother the admin.
  1032. if gdac.player_is_admin(targetname) then
  1033. return
  1034. end
  1035. if self.punch_target and self.punch_target(self, self.object, self.attack) == true then
  1036. -- If 'true', skip default punch action.
  1037. else
  1038. local damage = self.damage or 0
  1039. if self.damage_min and self.damage_max then
  1040. if self.damage_min > damage and self.damage_max >= self.damage_min then
  1041. damage = random(self.damage_min, self.damage_max)
  1042. end
  1043. end
  1044. local dgroup = self.damage_group or "fleshy"
  1045. self.attack:punch(self.object, 1.0, {
  1046. full_punch_interval = 1.0,
  1047. damage_groups = {[dgroup] = damage}
  1048. }, nil)
  1049. -- Start punch timer; mob cannot punch again until timer reaches 0.
  1050. self.punch_timer = 1
  1051. ambiance.sound_play("default_punch", p2, 2.0, 30)
  1052. end
  1053. -- Tell everyone about the death [MustTest].
  1054. if self.attack:is_player() and self.attack:get_hp() <= 0 then
  1055. mobs.mob_killed_player(self, self.attack)
  1056. self.attack = nil
  1057. end
  1058. end
  1059. -- Remove block if possible [MustTest]. Note: this function does not necessarily
  1060. -- have to break a node if it is non-walkable, but even if so (i.e., air) it
  1061. -- MUST still return true in that case!
  1062. local function try_break_block(self, s)
  1063. -- Must round position ourselves, otherwise we'll expose rounding
  1064. -- inconsistencies in the engine and possibly break protection.
  1065. s = v_round(s)
  1066. local node1 = minetest.get_node(s).name
  1067. -- Shortcut.
  1068. if node1 == "air" then
  1069. return true
  1070. end
  1071. -- Checks must be performed in order of severity.
  1072. local ndef1 = minetest.registered_nodes[node1]
  1073. -- Don't destroy player's bones [MustTest]!
  1074. if (not ndef1) or node1 == "ignore" or node1 == "bones:bones" then
  1075. return false, "special"
  1076. end
  1077. if ndef1.groups.unbreakable or ndef1.groups.immovable then
  1078. return false, "unbreakable"
  1079. end
  1080. -- Some liquids (like lava sources) are walkable. The liquid check must
  1081. -- therefore come first. (Some fake liquids, like nether grit, are diggable.)
  1082. if ndef1.groups.liquid and not ndef1.diggable then
  1083. return false, "liquid"
  1084. end
  1085. -- Check node level against mob's max-dig-level.
  1086. if (ndef1.groups.level or 0) > (self.max_node_dig_level or 1) then
  1087. return false, "unbreakable"
  1088. end
  1089. if ndef1.walkable and minetest.test_protection(s, "") then
  1090. return false, "protected"
  1091. end
  1092. -- If a non-walkable node is also NOT dangerous, it does not block pathfinder.
  1093. if not ndef1.walkable and not is_node_dangerous(node1) then
  1094. return true
  1095. end
  1096. -- If we reach here, node ought to be either walkable, either/or dangerous.
  1097. local oldnode = minetest.get_node(s)
  1098. minetest.set_node(s, {name = "air"})
  1099. -- Run script hook
  1100. for _, callback in ipairs(minetest.registered_on_dignodes) do
  1101. -- Deepcopy pos, oldnode, because callback can modify them
  1102. callback(table.copy(s), table.copy(oldnode), self.object)
  1103. end
  1104. minetest.check_for_falling(s)
  1105. -- This function takes both nodetables and nodenames.
  1106. -- Pass node names, because passing a node table gives wrong results.
  1107. local drops = minetest.get_node_drops(oldnode.name, "")
  1108. for _, item in pairs(drops) do
  1109. local p = {
  1110. x = s.x + random() / 2 - 0.25,
  1111. y = s.y + random() / 2 - 0.25,
  1112. z = s.z + random() / 2 - 0.25,
  1113. }
  1114. minetest.add_item(p, item)
  1115. end
  1116. return true -- success!
  1117. end
  1118. local function force_jump_up(self, height)
  1119. height = height or self.jump_height or 0
  1120. local v = self.object:get_velocity()
  1121. if height == 1 then
  1122. v.y = 5 -- Jump a bit over one node.
  1123. elseif height == 2 then
  1124. v.y = 6.8 -- Jump slightly over two nodes.
  1125. elseif height == 3 then
  1126. v.y = 8.2 -- Jump over three nodes.
  1127. else
  1128. v.y = 5
  1129. end
  1130. v.y = v.y + (random(-50, 50) / 100)
  1131. self.object:set_velocity(v)
  1132. set_animation(self, "jump")
  1133. end
  1134. -- Jump if facing a solid node while moving forward (not fences or gates).
  1135. -- This function returns true if mob jumped; otherwise 'false' + "reason".
  1136. -- Notice: this func DOES NOT rotate the mob under any circumstances.
  1137. local function try_jump(self, dtime)
  1138. -- Abort if mob does not have the ability to jump.
  1139. if not self.jump or self.jump_height == 0 or self.fly then
  1140. return false, "disabled"
  1141. end
  1142. -- Limit jump attempts to once per second.
  1143. self.jump_timer = (self.jump_timer or 0) - dtime
  1144. if self.jump_timer > 0 then
  1145. return false, "jumping"
  1146. end
  1147. self.jump_timer = 0
  1148. -- If we've only been stuck for less than a moment, we are still moving.
  1149. if self.stuck_timer < 0.5 then
  1150. return false, "moving"
  1151. end
  1152. -- We can only jump if standing on solid node.
  1153. if not minetest.registered_nodes[self.standing_on].walkable then
  1154. return false, "unwalkable"
  1155. end
  1156. -- What is in front of the mob?
  1157. local nodebot = self.facing_node
  1158. local nodetop = node_ok(v_add(self.facing_pos, {x=0, y=1, z=0}))
  1159. -- Is the mob facing a fence?
  1160. if self.facing_fence then
  1161. return false, "fence"
  1162. end
  1163. -- Is the node in front of the mob's head (assuming 2 node high mob) walkable?
  1164. local blocked = minetest.registered_nodes[nodetop.name].walkable
  1165. if blocked then
  1166. -- Only considered blocked if the mob can't jump 2 nodes high.
  1167. if self.jump_height < 2 then
  1168. return false, "blocked"
  1169. end
  1170. end
  1171. -- Is the node ahead NOT walkable? Something else is probably blocking us.
  1172. if not minetest.registered_nodes[nodebot].walkable then
  1173. return false, "walkable"
  1174. end
  1175. force_jump_up(self)
  1176. -- When in air move forward.
  1177. minetest.after(0.3, function(self, v)
  1178. if self.object:get_luaentity() then
  1179. local v = self.object:get_velocity()
  1180. self.object:set_acceleration({
  1181. x = v.x * 2,
  1182. y = 0,
  1183. z = v.z * 2,
  1184. })
  1185. end
  1186. end, self, v)
  1187. if get_velocity(self) > 0 then
  1188. mob_sound(self, self.sounds.jump)
  1189. end
  1190. -- Cannot jump again for one second.
  1191. self.jump_timer = 1
  1192. return true
  1193. end
  1194. -- Env damage avoidance extracted into its own function [MustTest].
  1195. local env_damage_nodes = {
  1196. "group:soil",
  1197. "group:stone",
  1198. "group:sand",
  1199. "group:rackstone",
  1200. "group:netherack",
  1201. node_ice,
  1202. node_snowblock,
  1203. }
  1204. -- Executed when self.state == "avoid" [MustTest].
  1205. -- Function assumes entity object exists (entity methods shall not return nil).
  1206. local function avoid_env_damage(self, dtime)
  1207. -- Get rounded position of the node the mob is standing in.
  1208. local s = self.object:get_pos()
  1209. s.y = s.y + self.collisionbox[2] + 0.5
  1210. s = v_round(s)
  1211. self.avoid.timer = self.avoid.timer - dtime
  1212. if self.avoid.timer <= 0 then
  1213. self.avoid.timer = 0
  1214. self.avoid.target = nil
  1215. end
  1216. -- Current target's timeout has expired. Need to find a new safe spot.
  1217. if self.avoid.timer <= 0 then
  1218. -- Get list of nearby safe nodes under air.
  1219. local minp = {x=s.x - 1, y=s.y - 0, z=s.z - 1}
  1220. local maxp = {x=s.x + 1, y=s.y + 1, z=s.z + 1}
  1221. local targets = minetest.find_nodes_in_area_under_air(
  1222. minp, maxp, env_damage_nodes)
  1223. -- Didn't find anything? Expand search area.
  1224. if #targets == 0 then
  1225. minp.x = minp.x - 2
  1226. minp.y = minp.y - 0
  1227. minp.z = minp.z - 2
  1228. maxp.x = maxp.x + 2
  1229. maxp.y = maxp.y + 1
  1230. maxp.z = maxp.z + 2
  1231. targets = minetest.find_nodes_in_area_under_air(
  1232. minp, maxp, env_damage_nodes)
  1233. end
  1234. -- Still didn't find anything? Expand search area again.
  1235. if #targets == 0 then
  1236. minp.x = minp.x - 2
  1237. minp.y = minp.y - 1
  1238. minp.z = minp.z - 2
  1239. maxp.x = maxp.x + 2
  1240. maxp.y = maxp.y + 1
  1241. maxp.z = maxp.z + 2
  1242. targets = minetest.find_nodes_in_area_under_air(
  1243. minp, maxp, env_damage_nodes)
  1244. end
  1245. -- Select position of random block to climb onto.
  1246. if #targets > 0 then
  1247. self.avoid.target = targets[random(1, #targets)]
  1248. self.avoid.timer = 3
  1249. end
  1250. end
  1251. -- Do we have a safe position?
  1252. if self.avoid.target then
  1253. if (self.pathfinding or 0) >= 1 then
  1254. self.path.target = v_add(self.avoid.target, {x=0, y=1, z=0})
  1255. self.path.dangerous_paths = true
  1256. push_state(self, "pathfind")
  1257. return
  1258. else
  1259. -- Look towards land and jump/move in that direction.
  1260. local yaw = yaw_to_pos(self, self.avoid.target, s)
  1261. set_yaw(self, yaw, 4)
  1262. set_velocity(self, self.run_velocity or 0)
  1263. set_animation(self, "run")
  1264. self.avoid.timer = 3
  1265. end
  1266. else
  1267. -- Mob panics, turns in random direction.
  1268. if self.avoid.timer <= 0 then
  1269. local yaw = self.object:get_yaw()
  1270. yaw = yaw + random(-pi, pi)
  1271. set_yaw(self, yaw, 6)
  1272. self.avoid.timer = 3
  1273. end
  1274. set_velocity(self, self.run_velocity or 0)
  1275. set_animation(self, "run")
  1276. end
  1277. end
  1278. local function do_avoid_enter(self)
  1279. self.avoid.target = nil
  1280. self.avoid.timer = 0
  1281. end
  1282. -- Blast damage to entities nearby (modified from TNT mod).
  1283. local function entity_physics(pos, radius)
  1284. radius = radius * 2
  1285. local objs = minetest.get_objects_inside_radius(pos, radius)
  1286. local obj_pos, dist
  1287. for n = 1, #objs do
  1288. obj_pos = objs[n]:get_pos()
  1289. dist = get_distance(pos, obj_pos)
  1290. if dist < 1 then dist = 1 end
  1291. local damage = floor((4 / dist) * radius)
  1292. local ent = objs[n]:get_luaentity()
  1293. -- punches work on entities and players
  1294. objs[n]:punch(objs[n], 1.0, {
  1295. full_punch_interval = 1.0,
  1296. damage_groups = {fleshy = damage},
  1297. }, pos)
  1298. end
  1299. end
  1300. -- Should mob follow what I'm holding?
  1301. local function follow_holding(self, clicker)
  1302. if not clicker:is_player() then
  1303. return false
  1304. end
  1305. local item = clicker:get_wielded_item()
  1306. local t = type(self.follow)
  1307. local name = item:get_name()
  1308. -- Single item.
  1309. if t == "string" and name == self.follow then
  1310. return true
  1311. -- Multiple items.
  1312. elseif t == "table" then
  1313. for i = 1, #self.follow, 1 do
  1314. if self.follow[i] == name then
  1315. return true
  1316. end
  1317. end
  1318. end
  1319. return false
  1320. end
  1321. -- Find two animals of same type and breed if nearby and horny.
  1322. -- Note: function is never called more than once per second. (No 'dtime' arg.)
  1323. local function attempt_breed(self)
  1324. -- Child takes 240 seconds before growing into adult.
  1325. if self.child == true then
  1326. self.hornytimer = self.hornytimer + 1
  1327. if self.hornytimer > 240 then
  1328. self.child = false
  1329. self.hornytimer = 0
  1330. self.object:set_properties({
  1331. textures = self.base_texture,
  1332. mesh = self.base_mesh,
  1333. visual_size = self.base_size,
  1334. collisionbox = self.base_colbox,
  1335. selectionbox = self.base_selbox,
  1336. })
  1337. -- custom function when child grows up
  1338. if self.on_grown then
  1339. self.on_grown(self)
  1340. else
  1341. -- jump when fully grown so as not to fall into ground
  1342. self.object:set_velocity({
  1343. x = 0,
  1344. y = 5,
  1345. z = 0
  1346. })
  1347. end
  1348. end
  1349. return
  1350. end
  1351. -- horny animal can mate for 40 seconds,
  1352. -- afterwards horny animal cannot mate again for 200 seconds
  1353. if self.horny == true
  1354. and self.hornytimer < 240 then
  1355. self.hornytimer = self.hornytimer + 1
  1356. if self.hornytimer >= 240 then
  1357. self.hornytimer = 0
  1358. self.horny = false
  1359. end
  1360. end
  1361. -- find another same animal who is also horny and mate if nearby
  1362. if self.horny == true
  1363. and self.hornytimer <= 40 then
  1364. local pos = self.object:get_pos()
  1365. effect({x = pos.x, y = pos.y + 1, z = pos.z}, 8, "heart.png", 3, 4, 1, 0.1)
  1366. local objs = minetest.get_objects_inside_radius(pos, 3)
  1367. local num = 0
  1368. local ent = nil
  1369. for n = 1, #objs do
  1370. ent = objs[n]:get_luaentity()
  1371. -- check for same animal with different colour
  1372. local canmate = false
  1373. if ent then
  1374. if ent.name == self.name then
  1375. canmate = true
  1376. else
  1377. local entname = string.split(ent.name,":")
  1378. local selfname = string.split(self.name,":")
  1379. if entname[1] == selfname[1] then
  1380. entname = string.split(entname[2],"_")
  1381. selfname = string.split(selfname[2],"_")
  1382. if entname[1] == selfname[1] then
  1383. canmate = true
  1384. end
  1385. end
  1386. end
  1387. end
  1388. if ent
  1389. and canmate == true
  1390. and ent.horny == true
  1391. and ent.hornytimer <= 40 then
  1392. num = num + 1
  1393. end
  1394. -- found your mate? then have a baby
  1395. if num > 1 then
  1396. self.hornytimer = 41
  1397. ent.hornytimer = 41
  1398. -- spawn baby
  1399. minetest.after(5, function(self, ent)
  1400. if not self.object:get_luaentity() then
  1401. return
  1402. end
  1403. -- custom breed function
  1404. if self.on_breed then
  1405. -- when false skip going any further
  1406. if self.on_breed(self, ent) == false then
  1407. return
  1408. end
  1409. else
  1410. effect(pos, 15, "tnt_smoke.png", 1, 2, 2, 15, 5)
  1411. end
  1412. local mob = minetest.add_entity(pos, self.name)
  1413. local ent2 = mob:get_luaentity()
  1414. local textures = self.base_texture
  1415. -- using specific child texture (if found)
  1416. if self.child_texture then
  1417. textures = self.child_texture[1]
  1418. end
  1419. -- and resize to half height
  1420. mob:set_properties({
  1421. textures = textures,
  1422. visual_size = {
  1423. x = self.base_size.x * .5,
  1424. y = self.base_size.y * .5,
  1425. },
  1426. collisionbox = {
  1427. self.base_colbox[1] * .5,
  1428. self.base_colbox[2] * .5,
  1429. self.base_colbox[3] * .5,
  1430. self.base_colbox[4] * .5,
  1431. self.base_colbox[5] * .5,
  1432. self.base_colbox[6] * .5,
  1433. },
  1434. selectionbox = {
  1435. self.base_selbox[1] * .5,
  1436. self.base_selbox[2] * .5,
  1437. self.base_selbox[3] * .5,
  1438. self.base_selbox[4] * .5,
  1439. self.base_selbox[5] * .5,
  1440. self.base_selbox[6] * .5,
  1441. },
  1442. })
  1443. -- tamed and owned by parents' owner
  1444. ent2.child = true
  1445. ent2.tamed = true
  1446. ent2.owner = self.owner
  1447. end, self, ent)
  1448. num = 0
  1449. break
  1450. end
  1451. end
  1452. end
  1453. end
  1454. -- Find and replace what mob is looking for (grass, wheat etc.).
  1455. local function replace(self, pos)
  1456. if not mobs_griefing
  1457. or not self.replace_rate
  1458. or not self.replace_what
  1459. or self.child == true
  1460. or self.object:get_velocity().y ~= 0
  1461. or random(1, self.replace_rate) > 1 then
  1462. return
  1463. end
  1464. local what, with, y_offset
  1465. if type(self.replace_what[1]) == "table" then
  1466. local num = random(#self.replace_what)
  1467. what = self.replace_what[num][1] or ""
  1468. with = self.replace_what[num][2] or ""
  1469. y_offset = self.replace_what[num][3] or 0
  1470. else
  1471. what = self.replace_what
  1472. with = self.replace_with or ""
  1473. y_offset = self.replace_offset or 0
  1474. end
  1475. pos.y = pos.y + y_offset
  1476. local range = self.replace_range or 1
  1477. local target = minetest.find_node_near(pos, range, what)
  1478. if target then
  1479. -- Do not disturb protected stuff.
  1480. if minetest.test_protection(target, "") then return end
  1481. -- print ("replace node = ".. minetest.get_node(pos).name, pos.y)
  1482. local oldnode = {name = what}
  1483. local newnode = {name = with}
  1484. local on_replace_return
  1485. if self.on_replace then
  1486. on_replace_return = self.on_replace(self, target, oldnode, newnode)
  1487. end
  1488. if on_replace_return ~= false then
  1489. minetest.add_node(target, {name = with})
  1490. -- when cow/sheep eats grass, replace wool and milk
  1491. if self.gotten == true then
  1492. self.gotten = false
  1493. self.object:set_properties(self)
  1494. end
  1495. end
  1496. end
  1497. end
  1498. -- Check if daytime and also if mob is docile during daylight hours.
  1499. local function day_docile(self)
  1500. if not self.docile_by_day then
  1501. return false
  1502. elseif self.time_of_day > 0.2 and self.time_of_day < 0.8 then
  1503. return true
  1504. end
  1505. end
  1506. -- Debug path display function.
  1507. local function highlight_path(self)
  1508. if not mobs.debug_paths then
  1509. return
  1510. end
  1511. if not self.path.following then
  1512. return
  1513. end
  1514. -- Show path using particles.
  1515. if self.path.way and #self.path.way > 0 then
  1516. local pname = "singleplayer"
  1517. if not minetest.is_singleplayer() then
  1518. pname = gdac.name_of_admin
  1519. end
  1520. for _, pos in ipairs(self.path.way) do
  1521. utility.original_add_particle({
  1522. playername = pname,
  1523. pos = pos,
  1524. velocity = {x=0, y=0, z=0},
  1525. acceleration = {x=0, y=0, z=0},
  1526. expirationtime = 1.5,
  1527. size = 4,
  1528. collisiondetection = false,
  1529. vertical = false,
  1530. texture = "heart.png",
  1531. })
  1532. end
  1533. end
  1534. end
  1535. -- Place node, excluding it from protection.
  1536. local function force_place_block(name, pos, bridge)
  1537. minetest.set_node(pos, {name=name})
  1538. local meta = minetest.get_meta(pos)
  1539. meta:set_int("protection_cancel", 1)
  1540. -- Drop node if the position underneath is not walkable and NOT bridging.
  1541. if not bridge then
  1542. if not pos_walkable(v_add(pos, {x=0, y=-1, z=0})) then
  1543. if not minetest.test_protection(pos, "") then
  1544. sfn.drop_node(pos)
  1545. end
  1546. else
  1547. minetest.check_for_falling(pos)
  1548. end
  1549. end
  1550. end
  1551. -- Function shall attempt to place a node, exluding it from protection.
  1552. local function try_place_block(self, target, bridge)
  1553. local pn = self.place_node or node_pathfinder_place
  1554. local nn = minetest.get_node(target).name
  1555. if nn == "air" or nn == "default:snow" then
  1556. force_place_block(pn, target, bridge)
  1557. return true
  1558. end
  1559. local ndef = minetest.registered_nodes[nn]
  1560. if not ndef or nn == "ignore" then
  1561. return false
  1562. end
  1563. if ndef.buildable_to and not minetest.test_protection(target, "") then
  1564. force_place_block(pn, target, bridge)
  1565. return true
  1566. end
  1567. end
  1568. -- Shall return true if blockage was fully removed [MustTest].
  1569. local function try_dig_doorway(self)
  1570. local p1 = get_ahead_pos(self)
  1571. -- First, try to break the block above.
  1572. -- If we can't do this, there's no point in trying to break the bottom block.
  1573. -- That would also interfere with us closing the bottom hole up.
  1574. p1.y = p1.y + 1
  1575. local b1
  1576. local b2 = try_break_block(self, p1)
  1577. p1.y = p1.y - 1
  1578. -- Sometimes, a mob is trying to path through a 1x1 hole, where the block
  1579. -- above is undiggable for some reason. I can do something clever here:
  1580. -- if the bottom hole is air, I can close it up. This way, the next time the
  1581. -- pathfinder runs, it will not try to go through this hole. [MustTest]
  1582. local hole_closed = false
  1583. if not b2 then
  1584. if try_place_block(self, p1) then
  1585. hole_closed = true
  1586. end
  1587. else
  1588. b1 = try_break_block(self, p1)
  1589. end
  1590. if b1 and b2 then
  1591. return true
  1592. elseif hole_closed then
  1593. return false, "changed"
  1594. else
  1595. return false, "failed"
  1596. end
  1597. end
  1598. -- Specific attack.
  1599. local function specific_attack(list, what)
  1600. -- No list so attack default (player, animals etc.)
  1601. if list == nil then
  1602. return true
  1603. end
  1604. -- is found entity on list to attack?
  1605. for no = 1, #list do
  1606. if list[no] == what then
  1607. return true
  1608. end
  1609. end
  1610. return false
  1611. end
  1612. -- Select nearest target entity from an array of entities.
  1613. local function select_nearest_entity(self, list)
  1614. local s = self.object:get_pos()
  1615. s.y = s.y + 1 -- Make easier to look up hills.
  1616. local closest_target
  1617. local current_distance = self.view_range + 1
  1618. -- Go through entities and select closest.
  1619. local size = #list -- Cache array length.
  1620. for n = 1, size, 1 do
  1621. local target = list[n]
  1622. local p = target:get_pos()
  1623. p.y = p.y + 1 -- Make easier to look up hills.
  1624. local dist = get_distance(p, s)
  1625. -- Choose closest target that is not self.
  1626. if dist > 0 then
  1627. if dist < current_distance and raycast_los(self, s, p) then
  1628. current_distance = dist
  1629. closest_target = target
  1630. end
  1631. end
  1632. end
  1633. return closest_target
  1634. end
  1635. -- Specific runaway.
  1636. local function specific_runaway(list, what)
  1637. -- No list.
  1638. if not list then return end
  1639. -- Found entity on list to run away from?
  1640. for no = 1, #list, 1 do
  1641. if list[no] == what then
  1642. return true
  1643. end
  1644. end
  1645. end
  1646. -- Get list of targets in area that should be run away from.
  1647. local function get_avoidable_targets(self)
  1648. local s = self.object:get_pos()
  1649. local objs = minetest.get_objects_inside_radius(s, self.view_range)
  1650. for n = 1, #objs, 1 do
  1651. local ent = objs[n]:get_luaentity()
  1652. -- Are we a player?
  1653. if objs[n]:is_player() then
  1654. local pname = objs[n]:get_player_name()
  1655. -- If player invisible them mob does not run away from them.
  1656. if mobs.is_invisible(self, pname) then
  1657. objs[n] = nil
  1658. goto continue
  1659. end
  1660. -- Ignore dead players.
  1661. if objs[n]:get_hp() <= 0 then
  1662. objs[n] = nil
  1663. goto continue
  1664. end
  1665. -- If player nametag is off, reduce range at which mob can see them.
  1666. if objs[n] and player_labels.query_nametag_onoff(pname) == false then
  1667. local r = self.view_range * 0.8
  1668. local p = objs[n]:get_pos()
  1669. if v_distance(p, s) > r then
  1670. objs[n] = nil
  1671. goto continue
  1672. end
  1673. end
  1674. -- Don't run from ignored players.
  1675. if minetest.check_player_privs(pname, {mobs_ignore=true}) then
  1676. objs[n] = nil
  1677. goto continue
  1678. end
  1679. -- Or are we a mob?
  1680. elseif ent and ent._cmi_is_mob then
  1681. -- Don't run away from mobs of our own type, or unknown type.
  1682. if ent.name == "" or self.name == ent.name then
  1683. objs[n] = nil
  1684. goto continue
  1685. end
  1686. -- Ignore mobs we don't care about.
  1687. if not specific_runaway(self.runaway_from, ent.name) then
  1688. objs[n] = nil
  1689. goto continue
  1690. end
  1691. -- Remove all other entities.
  1692. else
  1693. objs[n] = nil
  1694. goto continue
  1695. end
  1696. ::continue::
  1697. end
  1698. -- Compact targets into an array.
  1699. local targets = {}
  1700. local index = 1
  1701. for k, v in pairs(objs) do
  1702. targets[index] = v
  1703. index = index + 1
  1704. end
  1705. return targets
  1706. end
  1707. -- Get list of targets in area that can be attacked.
  1708. local function get_attackable_targets(self)
  1709. local s = self.object:get_pos()
  1710. local objs = minetest.get_objects_inside_radius(s, self.view_range)
  1711. -- Scan found entities and remove entities we aren't interested in.
  1712. for n = 1, #objs, 1 do
  1713. local ent = objs[n]:get_luaentity()
  1714. -- Are we a player?
  1715. if objs[n]:is_player() then
  1716. local pname = objs[n]:get_player_name()
  1717. -- If mob does not attack players.
  1718. if not self.attack_players then
  1719. objs[n] = nil
  1720. goto continue
  1721. end
  1722. -- If player is invisible (some mobs can ignore invisibility).
  1723. if mobs.is_invisible(self, pname) then
  1724. objs[n] = nil
  1725. goto continue
  1726. end
  1727. if not specific_attack(self.specific_attack, "player") then
  1728. objs[n] = nil
  1729. goto continue
  1730. end
  1731. -- Ignore dead players.
  1732. if objs[n]:get_hp() <= 0 then
  1733. objs[n] = nil
  1734. goto continue
  1735. end
  1736. -- If player nametag is off, reduce range at which mob can see them.
  1737. if player_labels.query_nametag_onoff(pname) == false then
  1738. local r = self.view_range * 0.8
  1739. local p = objs[n]:get_pos()
  1740. if v_distance(p, s) > r then
  1741. objs[n] = nil
  1742. goto continue
  1743. end
  1744. end
  1745. -- Don't attack ignored players.
  1746. if minetest.check_player_privs(pname, {mobs_ignore=true}) then
  1747. objs[n] = nil
  1748. goto continue
  1749. end
  1750. -- Or are we a mob?
  1751. elseif ent and ent._cmi_is_mob then
  1752. -- Remove mobs not to attack.
  1753. if self.name == ent.name
  1754. or (not self.attack_animals and ent.type == "animal")
  1755. or (not self.attack_monsters and ent.type == "monster")
  1756. or (not self.attack_npcs and ent.type == "npc")
  1757. or not specific_attack(self.specific_attack, ent.name) then
  1758. objs[n] = nil
  1759. goto continue
  1760. end
  1761. -- Remove all other entities.
  1762. else
  1763. objs[n] = nil
  1764. goto continue
  1765. end
  1766. ::continue::
  1767. end
  1768. -- Compact targets into an array.
  1769. local targets = {}
  1770. local index = 1
  1771. for k, v in pairs(objs) do
  1772. targets[index] = v
  1773. index = index + 1
  1774. end
  1775. return targets
  1776. end
  1777. -- General attack function for all mobs. Scan for targets and attack them.
  1778. -- This function (usually) only executes once per second (per mob) [MustTest].
  1779. local function general_attack(self)
  1780. -- Skip because mob is passive.
  1781. if self.passive then return end
  1782. -- Skip because already attacking something, or running away.
  1783. if self.state == "attack" then return end
  1784. if self.state == "runaway" then return end
  1785. if self.state == "pathfind" then return end
  1786. if self.state == "avoid" then return end
  1787. if self.state == "digbuild" then return end
  1788. -- Skip if mob is docile during day.
  1789. if day_docile(self) then return end
  1790. -- Get array list of targets to attack.
  1791. local objs = get_attackable_targets(self)
  1792. local target = select_nearest_entity(self, objs)
  1793. -- Attack closest target.
  1794. if target and random(1, 100) < (self.attack_chance or 95) then
  1795. do_attack(self, target)
  1796. return
  1797. end
  1798. -- Hunt random nearby target. (Allows targets outside of LOS.)
  1799. if #objs > 0 then
  1800. if not target and random(1, 100) < (self.hunt_chance or 5) then
  1801. local tarhunt = objs[random(1, #objs)]
  1802. do_attack(self, tarhunt)
  1803. return
  1804. end
  1805. end
  1806. end
  1807. -- Find someone to runaway from.
  1808. local function runaway_from(self)
  1809. -- Abort if mob doesn't fear any particular enemies.
  1810. if not self.runaway_from then return end
  1811. -- If non-passive mob is attacking, then it will not run away right now.
  1812. if self.state == "attack" and not self.passive then return end
  1813. if self.state == "runaway" then return end
  1814. if self.state == "pathfind" then return end
  1815. if self.state == "avoid" then return end
  1816. -- Get array list of targets to run away from.
  1817. local objs = get_avoidable_targets(self)
  1818. local target = select_nearest_entity(self, objs)
  1819. if target then
  1820. local s = self.object:get_pos()
  1821. local p = target:get_pos()
  1822. local yaw = yaw_to_pos(self, p, s)
  1823. yaw = yaw + pi -- Face opposite.
  1824. set_yaw(self, yaw, 4)
  1825. transition_state(self, "runaway")
  1826. end
  1827. end
  1828. -- Get an object ref to the mob's owner if in view range.
  1829. local function get_owner_in_range(self)
  1830. if not self.owner or self.owner == "" then
  1831. return
  1832. end
  1833. -- Only players can be mob owners.
  1834. local players = minetest.get_connected_players()
  1835. for i = 1, #players, 1 do
  1836. local pref = players[i]
  1837. local pname = pref:get_player_name()
  1838. if pname == self.owner then
  1839. local s = self.object:get_pos()
  1840. local p = pref:get_pos()
  1841. if v_distance(s, p) < self.view_range then
  1842. s.y = s.y + 1
  1843. p.y = p.y + 1
  1844. if raycast_los(self, s, p) then
  1845. -- Do not return player ref if player is ignored.
  1846. if not minetest.check_player_privs(pname, {mobs_ignore=true}) then
  1847. return pref
  1848. end
  1849. end
  1850. end
  1851. end
  1852. end
  1853. end
  1854. local function get_follow_holding_in_range(self)
  1855. if not self.follow or self.follow == "" then
  1856. return
  1857. end
  1858. -- Only players can hold items that mob might follow.
  1859. local players = minetest.get_connected_players()
  1860. for i = 1, #players, 1 do
  1861. local pref = players[i]
  1862. local s = self.object:get_pos()
  1863. local p = pref:get_pos()
  1864. if v_distance(s, p) < self.view_range then
  1865. if follow_holding(self, pref) then
  1866. s.y = s.y + 1
  1867. p.y = p.y + 1
  1868. if raycast_los(self, s, p) then
  1869. local pname = pref:get_player_name()
  1870. if not minetest.check_player_privs(pname, {mobs_ignore=true}) then
  1871. return pref
  1872. end
  1873. end
  1874. end
  1875. end
  1876. end
  1877. end
  1878. -- Check nearby players and follow them if conditions are right.
  1879. -- Shall follow player if player is mob's owner, or if holding item.
  1880. local function follow_something(self)
  1881. -- Skip if attacking or running away.
  1882. if self.state == "attack" then return end
  1883. if self.state == "runaway" then return end
  1884. if self.state == "avoid" then return end
  1885. if self.state == "pathfind" then return end
  1886. -- Skip if already following.
  1887. if self.following and self.following:get_pos() then return end
  1888. -- Skip if horny (who comes up with these terms? Geez).
  1889. if self.horny then return end
  1890. -- Skip if mob is child.
  1891. if self.child then return end
  1892. -- If the mob has an owner nearby, follow him!
  1893. local owner = get_owner_in_range(self)
  1894. if owner then
  1895. local pname = owner:get_player_name()
  1896. if not mobs.is_invisible(self, pname) then
  1897. self.following = owner
  1898. transition_state(self, "follow")
  1899. return
  1900. end
  1901. end
  1902. local holding = get_follow_holding_in_range(self)
  1903. if holding then
  1904. local pname = holding:get_player_name()
  1905. if not mobs.is_invisible(self, pname) then
  1906. self.following = holding
  1907. transition_state(self, "follow")
  1908. return
  1909. end
  1910. end
  1911. end
  1912. -- If the mob has a target, and LOS to target for time, then refocus attack!
  1913. -- This function expects to run once per second.
  1914. local function refocus_attack(self)
  1915. if not self.attack then
  1916. self.refocus_timer = 0
  1917. return
  1918. end
  1919. local s = self.object:get_pos()
  1920. local p = self.attack:get_pos()
  1921. if not p then
  1922. self.refocus_timer = 0
  1923. return
  1924. end
  1925. -- Make looking up hills easier.
  1926. s.y = s.y + 1
  1927. p.y = p.y + 1
  1928. local los = raycast_los(self, s, p)
  1929. -- Count consecutive seconds in which mob has LOS to active target.
  1930. if los then
  1931. self.refocus_timer = (self.refocus_timer or 0) + 1
  1932. else
  1933. self.refocus_timer = 0
  1934. return
  1935. end
  1936. -- The counter limit is arbitrary.
  1937. if self.refocus_timer >= 8 then
  1938. transition_state(self, "attack")
  1939. return
  1940. end
  1941. end
  1942. -- Dogshoot attack switch and counter function.
  1943. local function dogswitch(self, dtime)
  1944. -- Switch mode not activated.
  1945. if not self.dogshoot_switch or not dtime then
  1946. return 0
  1947. end
  1948. -- Run timer.
  1949. self.dogshoot_count = self.dogshoot_count + dtime
  1950. local expired
  1951. if self.dogshoot_switch == 1 and self.dogshoot_count > self.dogshoot_count_max then
  1952. expired = true
  1953. elseif self.dogshoot_switch == 2 and self.dogshoot_count > self.dogshoot_count2_max then
  1954. expired = true
  1955. end
  1956. if expired then
  1957. -- Reset timer.
  1958. self.dogshoot_count = 0
  1959. -- Toggle.
  1960. if self.dogshoot_switch == 1 then
  1961. self.dogshoot_switch = 2
  1962. else
  1963. self.dogshoot_switch = 1
  1964. end
  1965. end
  1966. return self.dogshoot_switch
  1967. end
  1968. local function do_stand_enter(self)
  1969. set_velocity(self, 0)
  1970. set_animation(self, "stand")
  1971. end
  1972. -- State self.state == "stand" moved to its own function [MustTest].
  1973. local function do_stand_state(self, dtime)
  1974. -- Avoid dangerous nodes.
  1975. if is_node_dangerous(self, self.standing_in) then
  1976. push_state(self, "avoid")
  1977. return
  1978. end
  1979. local s = self.object:get_pos()
  1980. if keep_mob_centered(self, s) then
  1981. return
  1982. end
  1983. -- NPCs look at any players nearby, otherwise turn randomly.
  1984. if random(1, 4) == 1 then
  1985. local lp = nil
  1986. if self.type == "npc" then
  1987. local objs = minetest.get_objects_inside_radius(s, 10)
  1988. for n = 1, #objs, 1 do
  1989. if objs[n]:is_player() then
  1990. lp = objs[n]:get_pos()
  1991. break
  1992. end
  1993. end
  1994. -- Small chance that player gets ignored.
  1995. if random(1, 4) == 1 then
  1996. lp = nil
  1997. end
  1998. end
  1999. local yaw = self.object:get_yaw()
  2000. if lp then
  2001. yaw = yaw_to_pos(self, lp, s)
  2002. else
  2003. yaw = yaw + random(-0.5, 0.5)
  2004. end
  2005. set_yaw(self, yaw, 8)
  2006. end
  2007. set_velocity(self, 0)
  2008. set_animation(self, "stand")
  2009. -- Mobs ordered to stand stay standing.
  2010. if self.order == "stand" then return end
  2011. -- Am I facing something dangerous?
  2012. local result, reason = facing_wall_or_pit(self)
  2013. if result then return end
  2014. -- Animals are restricted by fences.
  2015. if self.type == "animal" and self.facing_fence then
  2016. return
  2017. end
  2018. if random(1, 100) > (self.walk_chance or 0) then
  2019. return
  2020. end
  2021. transition_state(self, "walk")
  2022. --[[ fly up/down randomly for flying mobs
  2023. if self.fly and random(1, 100) <= self.walk_chance then
  2024. local v = self.object:get_velocity()
  2025. local ud = random(-1, 2) / 9
  2026. self.object:set_velocity({x = v.x, y = ud, z = v.z})
  2027. end--]]
  2028. end
  2029. local function do_walk_enter(self)
  2030. set_velocity(self, self.walk_velocity or 0)
  2031. set_animation(self, "walk")
  2032. end
  2033. -- State self.state == "walk" moved to its own function [MustTest].
  2034. local function do_walk_state(self, dtime)
  2035. -- Avoid dangerous nodes.
  2036. if is_node_dangerous(self, self.standing_in) then
  2037. push_state(self, "avoid")
  2038. return
  2039. end
  2040. -- Am I facing something dangerous?
  2041. local result, reason = facing_wall_or_pit(self)
  2042. if result then
  2043. transition_state(self, "stand")
  2044. return
  2045. end
  2046. if self.type == "animal" and self.facing_fence then
  2047. transition_state(self, "stand")
  2048. return
  2049. end
  2050. -- Chance to stop walking.
  2051. if random(1, 100) <= 30 then
  2052. transition_state(self, "stand")
  2053. return
  2054. end
  2055. -- Randomly turn.
  2056. if random(1, 100) <= 30 then
  2057. local yaw = self.object:get_yaw()
  2058. yaw = yaw + random(-0.5, 0.5)
  2059. set_yaw(self, yaw, 8)
  2060. end
  2061. set_velocity(self, self.walk_velocity or 0)
  2062. if flight_check(self)
  2063. and self.animation
  2064. and self.animation.fly_start
  2065. and self.animation.fly_end then
  2066. set_animation(self, "fly")
  2067. else
  2068. set_animation(self, "walk")
  2069. end
  2070. end
  2071. local function do_runaway_enter(self)
  2072. self.runaway_timer = 5
  2073. end
  2074. -- Runaway (self.state == "runaway") moved to its own function [MustTest].
  2075. -- Note: this function executes once per frame ('continuous is true').
  2076. local function do_runaway_state(self, dtime)
  2077. self.runaway_timer = (self.runaway_timer or 0) - dtime
  2078. if self.runaway_timer <= 0 then
  2079. -- Timer has expired. Should we keep running, or stop?
  2080. local objs = get_avoidable_targets(self)
  2081. local target = select_nearest_entity(self, objs)
  2082. if target then
  2083. self.runaway_timer = 5
  2084. else
  2085. pop_state(self)
  2086. return
  2087. end
  2088. end
  2089. -- Do evasion if inside dangerous node.
  2090. if is_node_dangerous(self, self.standing_in) then
  2091. push_state(self, "avoid")
  2092. return
  2093. end
  2094. -- Stop fleeing if heading into obstacle.
  2095. local result, reason = facing_wall_or_pit(self)
  2096. if result then
  2097. pop_state(self)
  2098. return
  2099. end
  2100. try_jump(self, dtime)
  2101. set_velocity(self, self.sprint_velocity or 0)
  2102. set_animation(self, "run")
  2103. end
  2104. local function do_avoid_state(self, dtime)
  2105. if is_node_dangerous(self, self.standing_in) then
  2106. avoid_env_damage(self, dtime)
  2107. else
  2108. pop_state(self)
  2109. end
  2110. end
  2111. -- Mob has caught up with target.
  2112. local function do_caught_attack(self, dtime)
  2113. -- Target might not be valid anymore.
  2114. if not self.attack or not self.attack:get_pos() then
  2115. pop_state(self)
  2116. return
  2117. end
  2118. local s = self.object:get_pos()
  2119. local p = self.attack:get_pos()
  2120. local dist = get_distance(p, s)
  2121. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2122. -- Stop attacking if target invisible, dead, or out of range.
  2123. if dist > self.view_range or self.attack:get_hp() <= 0
  2124. or mobs.is_invisible(self, targetname) then
  2125. pop_state(self)
  2126. return
  2127. end
  2128. -- Start chasing again if target moved beyond reach.
  2129. if dist > self.reach then
  2130. transition_substate(self, "chase")
  2131. return
  2132. end
  2133. -- Stop and face target.
  2134. do
  2135. set_velocity(self, 0)
  2136. local yaw = yaw_to_pos(self, p, s)
  2137. set_yaw(self, yaw)
  2138. end
  2139. -- If mob does not have a custom attack, or that function returns true, then
  2140. -- execute the default punch-attack code.
  2141. if not self.custom_attack or self.custom_attack(self, p) == true then
  2142. set_animation(self, "punch")
  2143. punch_target(self, dtime)
  2144. end
  2145. end
  2146. -- Mob is blocked from reaching target by environment, etc.
  2147. local function do_blocked_attack(self, dtime)
  2148. -- Target might not be valid anymore.
  2149. if not self.attack or not self.attack:get_pos() then
  2150. pop_state(self)
  2151. return
  2152. end
  2153. -- Avoid dangerous nodes.
  2154. if is_node_dangerous(self, self.standing_in) then
  2155. push_state(self, "avoid")
  2156. return
  2157. end
  2158. local s = self.object:get_pos()
  2159. local p = self.attack:get_pos()
  2160. local dist = get_distance(p, s)
  2161. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2162. -- Stop attacking if target invisible, dead, or out of range.
  2163. if dist > self.view_range or self.attack:get_hp() <= 0
  2164. or mobs.is_invisible(self, targetname) then
  2165. pop_state(self)
  2166. return
  2167. end
  2168. -- Turn to face target. If the target moves around we may eventually become
  2169. -- unblocked.
  2170. do
  2171. set_velocity(self, 0)
  2172. set_animation(self, "stand")
  2173. local yaw = yaw_to_pos(self, p, s)
  2174. set_yaw(self, yaw)
  2175. end
  2176. -- Punch target if within punching range even while stuck [MustTest].
  2177. if dist <= (self.punch_reach or self.reach or 0) then
  2178. punch_target(self, dtime)
  2179. end
  2180. -- If dogshooter, transition to shoot once dogshoot timer expires.
  2181. -- This attack works even while mob is stuck.
  2182. if self.attack_type == "dogshoot" then
  2183. local switch = dogswitch(self, dtime)
  2184. if switch == 1 then
  2185. transition_substate(self, "shoot")
  2186. return
  2187. end
  2188. end
  2189. -- Flag set if mob is directly over or under player. If that is the case, but
  2190. -- we're still beyond the mob's reach, then we have to try something else ....
  2191. local overunder = false
  2192. if abs(s.x - p.x) < 0.5 and abs(s.z - p.z) < 0.5 then
  2193. overunder = true
  2194. end
  2195. if dist < self.reach then
  2196. transition_substate(self, "chase")
  2197. return
  2198. end
  2199. -- If mob facing obstacle, or directly over/under target, then we're stuck.
  2200. if overunder or facing_wall_or_pit(self) then
  2201. -- Mob is stuck and has been standing for 3 seconds.
  2202. if (self.pathfinding or 0) >= 1 and self.stand_timer > 3 then
  2203. self.path.dangerous_paths = false
  2204. self.path.target = v_round(self.attack:get_pos())
  2205. push_state(self, "pathfind")
  2206. return
  2207. end
  2208. else
  2209. -- Otherwise, not facing obstacle and NOT over/under target. Chase!
  2210. transition_substate(self, "chase")
  2211. return
  2212. end
  2213. end
  2214. local function do_chase_attack(self, dtime)
  2215. -- Target might not be valid anymore.
  2216. if not self.attack or not self.attack:get_pos() then
  2217. pop_state(self)
  2218. return
  2219. end
  2220. local s = self.object:get_pos()
  2221. local p = self.attack:get_pos()
  2222. local dist = get_distance(p, s)
  2223. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2224. -- Stop attacking if target invisible, dead, or out of range.
  2225. if dist > self.view_range or self.attack:get_hp() <= 0
  2226. or mobs.is_invisible(self, targetname) then
  2227. pop_state(self)
  2228. return
  2229. end
  2230. -- If dogshooter, transition to shoot once dogshoot timer expires.
  2231. if self.attack_type == "dogshoot" then
  2232. local switch = dogswitch(self, dtime)
  2233. if switch == 1 then
  2234. transition_substate(self, "shoot")
  2235. return
  2236. end
  2237. end
  2238. local dist = get_distance(p, s)
  2239. -- TODO: must use set_velocity (for fliers) here, not directly!
  2240. if self.fly and dist > self.reach then
  2241. local me_y = floor(s.y + 1)
  2242. local p_y = floor(p.y + 1)
  2243. local v = self.object:get_velocity()
  2244. if flight_check(self, s) then
  2245. if me_y < p_y then
  2246. -- Fly up.
  2247. self.object:set_velocity({
  2248. x = v.x,
  2249. y = 1 * self.walk_velocity,
  2250. z = v.z
  2251. })
  2252. elseif me_y > p_y then
  2253. -- Fly down.
  2254. self.object:set_velocity({
  2255. x = v.x,
  2256. y = -1 * self.walk_velocity,
  2257. z = v.z
  2258. })
  2259. end
  2260. else
  2261. if me_y < p_y then
  2262. -- Fly up slowly.
  2263. self.object:set_velocity({
  2264. x = v.x,
  2265. y = 0.01,
  2266. z = v.z
  2267. })
  2268. elseif me_y > p_y then
  2269. -- Fly down slowly.
  2270. self.object:set_velocity({
  2271. x = v.x,
  2272. y = -0.01,
  2273. z = v.z
  2274. })
  2275. end
  2276. end
  2277. end
  2278. -- Face target.
  2279. do
  2280. local yaw = yaw_to_pos(self, p, s)
  2281. set_yaw(self, yaw)
  2282. end
  2283. -- Flag set if mob is directly over or under player. If that is the case, but
  2284. -- we're still beyond the mob's reach, then we have to try something else ....
  2285. local overunder = false
  2286. if abs(s.x - p.x) < 0.5 and abs(s.z - p.z) < 0.5 then
  2287. overunder = true
  2288. end
  2289. -- Move towards enemy if beyond mob reach.
  2290. if dist > self.reach then
  2291. -- Note: the 'facing_wall_or_pit' function also checks for dangerous nodes.
  2292. -- But some dangerous nodes are non-walkable, which means the pathfinder
  2293. -- would path through them.
  2294. if facing_wall_or_pit(self) or overunder or self.stuck_timer > 1 then
  2295. -- Chase blocked, NOT pathfind blocked.
  2296. transition_substate(self, "blocked")
  2297. else
  2298. try_jump(self, dtime)
  2299. if dist > self.punch_reach then
  2300. set_velocity(self, self.sprint_velocity or 0)
  2301. set_animation(self, "run")
  2302. else
  2303. set_velocity(self, self.run_velocity or 0)
  2304. set_animation(self, "run")
  2305. end
  2306. end
  2307. -- Punch target if within punching range even while moving [MustTest].
  2308. if dist <= (self.punch_reach or self.reach or 0) then
  2309. punch_target(self, dtime)
  2310. end
  2311. else
  2312. -- Inside 'self.reach' range.
  2313. transition_substate(self, "caught")
  2314. end
  2315. end
  2316. local function do_shoot_attack(self, dtime)
  2317. -- Target might not be valid anymore.
  2318. if not self.attack or not self.attack:get_pos() then
  2319. pop_state(self)
  2320. return
  2321. end
  2322. local s = self.object:get_pos()
  2323. local p = self.attack:get_pos()
  2324. local dist = get_distance(p, s)
  2325. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2326. -- Stop attacking if target invisible, dead, or out of range.
  2327. if dist > self.view_range or self.attack:get_hp() <= 0
  2328. or mobs.is_invisible(self, targetname) then
  2329. pop_state(self)
  2330. return
  2331. end
  2332. p.y = p.y - 0.5
  2333. s.y = s.y + 0.5
  2334. -- If dogshooter, transition to chase once dogshoot timer expires.
  2335. if self.attack_type == "dogshoot" then
  2336. local switch = dogswitch(self, dtime)
  2337. if switch ~= 1 then
  2338. transition_substate(self, "chase")
  2339. return
  2340. end
  2341. end
  2342. -- Face target and stand.
  2343. local yaw = yaw_to_pos(self, p, s)
  2344. set_yaw(self, yaw)
  2345. set_velocity(self, 0)
  2346. set_animation(self, "shoot")
  2347. self.shoot_timer = (self.shoot_timer or 0) + dtime
  2348. if self.shoot_timer > (self.shoot_interval or 1) then
  2349. self.shoot_timer = 0
  2350. -- Shoot in this direction.
  2351. local vec = {
  2352. x = p.x - s.x,
  2353. y = p.y - s.y,
  2354. z = p.z - s.z,
  2355. }
  2356. shoot_arrow(self, vec)
  2357. end
  2358. end
  2359. local function do_attack_enter(self)
  2360. if random(0, 100) < 90 and self.sounds.war_cry then
  2361. mob_sound(self, self.sounds.war_cry)
  2362. end
  2363. end
  2364. local function do_attack_exit(self)
  2365. end
  2366. -- State self.state == "attack" extracted to its own function [MustTest].
  2367. -- The attack routines (explode, dogfight, shoot, dogshoot, etc.). This function
  2368. -- runs once per frame, while the "attack" state is active.
  2369. local function do_attack_state(self, dtime)
  2370. -- Abort if we have no target!
  2371. if not self.attack or not self.attack:get_pos() then
  2372. pop_state(self)
  2373. return
  2374. end
  2375. -- Calculate distance from mob and enemy.
  2376. local s = self.object:get_pos()
  2377. local p = self.attack:get_pos()
  2378. -- Abort if target entity does not exist.
  2379. if not p then
  2380. pop_state(self)
  2381. return
  2382. end
  2383. local dist = get_distance(p, s)
  2384. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2385. -- Stop attacking if target invisible, dead, or out of range.
  2386. if dist > self.view_range or self.attack:get_hp() <= 0
  2387. or mobs.is_invisible(self, targetname) then
  2388. pop_state(self)
  2389. return
  2390. end
  2391. local attack_type = self.attack_type
  2392. -- The special "dogshoot" attack type basically just swaps between "dogfight"
  2393. -- and "shoot" based on timers.
  2394. if attack_type == "dogshoot" then
  2395. local switch = dogswitch(self, dtime)
  2396. if switch == 1 then
  2397. attack_type = "shoot"
  2398. else
  2399. -- If 'dogswitch' returns 0 or 2, mob shall dogfight.
  2400. attack_type = "dogfight"
  2401. end
  2402. end
  2403. if attack_type == "dogfight" then
  2404. transition_substate(self, "chase")
  2405. elseif attack_type == "shoot" then
  2406. transition_substate(self, "shoot")
  2407. end
  2408. end
  2409. -- Code to handle mob's lifetimer extracted to own function [MustTest].
  2410. local function do_lifetimer(self, pos)
  2411. if self.tamed then return end
  2412. if self.type == "npc" then return end
  2413. if self.state == "attack" then return end
  2414. if self.lifetimer > 20000 then return end
  2415. if not remove_far then return end
  2416. self.lifetimer = self.lifetimer - dtime
  2417. if self.lifetimer > 0 then return end
  2418. -- Only despawn away from player
  2419. local objs = minetest.get_objects_inside_radius(pos, 15)
  2420. for n = 1, #objs, 1 do
  2421. if objs[n]:is_player() then
  2422. self.lifetimer = 20
  2423. return
  2424. end
  2425. end
  2426. effect(pos, 15, "tnt_smoke.png", 2, 4, 2, 0)
  2427. -- Mark for removal as last action on mob_step().
  2428. self.mkrm = true
  2429. end
  2430. -- This function gets the position of the node the mob is standing IN.
  2431. -- The node position around its feet, basically.
  2432. local function get_standing_pos(self, pos)
  2433. -- Copy position argument so we do not modify it.
  2434. local p = (pos and vector.copy(pos)) or self.object:get_pos()
  2435. local y = self.collisionbox[2]
  2436. if self.child then
  2437. y = self.collisionbox[2] * 0.5
  2438. end
  2439. p.y = p.y + y + 0.25
  2440. p = v_round(p)
  2441. return p
  2442. end
  2443. -- Code to get what mob is standing in/on extracted to own function [MustTest].
  2444. local function update_foot_nodes(self, pos, dtime)
  2445. -- Get node at foot level every quarter second.
  2446. self.node_timer = (self.node_timer or 0) + dtime
  2447. if self.node_timer > 0.25 then
  2448. self.node_timer = 0
  2449. -- What is mob standing in and on?
  2450. local spos = get_standing_pos(self, pos)
  2451. self.standing_in = node_ok(spos, "air").name
  2452. spos.y = spos.y - 1
  2453. self.standing_on = node_ok(spos, "air").name
  2454. -- What is mob facing?
  2455. self.facing_pos = get_ahead_pos(self, pos)
  2456. self.facing_node = node_ok(self.facing_pos, "air").name
  2457. -- Are we facing a fence or wall?
  2458. local fn = self.facing_node
  2459. if fn:find("fence") or fn:find("gate") or fn:find("wall") then
  2460. self.facing_fence = true
  2461. else
  2462. self.facing_fence = false
  2463. end
  2464. end
  2465. end
  2466. -- Get the absolute delta angle between two yaw angles, in radians.
  2467. function yaw_delta(y1, y2)
  2468. local y
  2469. -- First, get the difference between the two yaws.
  2470. if y1 > y2 then
  2471. y = y1 - y2
  2472. else
  2473. y = y2 - y1
  2474. end
  2475. -- Subtract PI if needed to get the smaller delta.
  2476. if y > pi then
  2477. y = y - (pi * 2)
  2478. end
  2479. return abs(y)
  2480. end
  2481. -- Detect whether a waypoint path contains sharp turns. This function checks the
  2482. -- mob's current yaw against the next 3 waypoints. If its yaw to each waypoint
  2483. -- is within a small tolerance, the path is straight; otherwise it is not.
  2484. local function path_is_straight(self, pos)
  2485. local path = self.path.way
  2486. if not path then return end
  2487. local w1 = path[1]
  2488. local w2 = path[2]
  2489. local w3 = path[3]
  2490. if not w1 or not w2 or not w3 then
  2491. return
  2492. end
  2493. local y1 = self.object:get_yaw()
  2494. local y2 = yaw_to_pos(self, w1, pos)
  2495. local y3 = yaw_to_pos(self, w2, pos)
  2496. local y4 = yaw_to_pos(self, w3, pos)
  2497. local d1 = deg(yaw_delta(y1, y2))
  2498. local d2 = deg(yaw_delta(y1, y3))
  2499. local d3 = deg(yaw_delta(y1, y4))
  2500. return (d1 < 15 and d2 < 10 and d3 < 5)
  2501. end
  2502. local function do_pathfind_enter(self)
  2503. -- The pathfinder requires a target. I assume the target is a rounded vector.
  2504. -- It should be inside an air node, or non-walkable, and walkable node under.
  2505. if not self.path.target then
  2506. pop_state(self)
  2507. return
  2508. end
  2509. transition_substate(self, "newpath")
  2510. end
  2511. local function do_pathfind_newpath(self, dtime)
  2512. -- Make sure to round positions, because the pathfinder is very sensitive.
  2513. local start = self.object:get_pos()
  2514. start.y = start.y + self.collisionbox[2] + 0.5
  2515. start = v_round(start)
  2516. -- The mob might be clipped inside a node. Find a start position nearby.
  2517. if pos_walkable(start) then
  2518. local minp = v_add(start, {x=-1, y=0, z=-1})
  2519. local maxp = v_add(start, {x=1, y=0, z=1})
  2520. local positions = hb4.find_walkable_in_area_under_unwalkable(minp, maxp)
  2521. if #positions == 0 then
  2522. transition_state(self, "")
  2523. return
  2524. else
  2525. start = positions[random(1, #positions)]
  2526. end
  2527. end
  2528. local target = v_round(self.path.target)
  2529. local radius = self.pathing_radius or 16
  2530. -- The target might not always be reachable (e.g., the target is a player who
  2531. -- has sneak-moved off the edge of a node, and thus are "standing" in air). So
  2532. -- we choose a random valid position near the target instead of the target
  2533. -- itself. We also check if the player is slightly clipped inside walkable.
  2534. if pos_walkable(target) or not pos_walkable(v_add(target, {x=0, y=-1, z=0})) then
  2535. local minp = v_add(target, {x=-2, y=-1, z=-2})
  2536. local maxp = v_add(target, {x=2, y=1, z=2})
  2537. local positions = hb4.find_walkable_in_area_under_unwalkable(minp, maxp)
  2538. if #positions == 0 then
  2539. if (self.pathfinding or 0) >= 3 then
  2540. -- Replace pathfinder with dig/build code.
  2541. -- The dig/build code should swap back to the pathfinder when ready.
  2542. self.digbuild.target = self.path.target
  2543. pop_state(self)
  2544. push_state(self, "digbuild")
  2545. return
  2546. end
  2547. transition_state(self, "")
  2548. return
  2549. else
  2550. target = positions[random(1, #positions)]
  2551. end
  2552. end
  2553. local dh = 6
  2554. local jh = 0
  2555. if self.fear_height ~= 0 then dh = (self.fear_height - 1) end
  2556. if self.stepheight > 1 then jh = 1 end
  2557. -- Do not generate paths with a jump-height above 3 nodes.
  2558. if self.jump then
  2559. if self.jump_height >= 3 then
  2560. jh = 3
  2561. elseif self.jump_height >= 2 then
  2562. jh = 2
  2563. elseif self.jump_height >= 1 then
  2564. jh = 1
  2565. end
  2566. end
  2567. -- Note: pathfinder is very sensitive to start and finish positions.
  2568. local path = minetest.find_path(start, target, radius, jh, dh, "A*")
  2569. if path then
  2570. -- Yay, I found path.
  2571. if self.attack and self.attack:get_pos() then
  2572. mob_sound(self, self.sounds.war_cry)
  2573. else
  2574. mob_sound(self, self.sounds.random)
  2575. end
  2576. self.path.way = path
  2577. self.path.following = true
  2578. self.path.blocked_count = 0
  2579. self.path.waypoints_gotten = 0
  2580. transition_substate(self, "")
  2581. return
  2582. else
  2583. if (self.pathfinding or 0) >= 3 then
  2584. -- Replace pathfinder with dig/build code.
  2585. -- The dig/build code should swap back to the pathfinder when ready.
  2586. self.digbuild.target = self.path.target
  2587. pop_state(self)
  2588. push_state(self, "digbuild")
  2589. return
  2590. end
  2591. transition_state(self, "")
  2592. return
  2593. end
  2594. end
  2595. -- In order to correctly follow a path, this function requires to be called once
  2596. -- per frame. This property is specified in the state machine table.
  2597. local function do_pathfind_state(self, dtime)
  2598. if not self.path.following or not self.path.way then
  2599. transition_state(self, "")
  2600. return
  2601. end
  2602. -- No very long paths [MustTest]. Note that the engine is now a lot better at
  2603. -- pathfinding, so bad paths aren't often generated anymore. I can leave the
  2604. -- limit fairly high.
  2605. local max_len = (self.pathing_radius or 16) * 4
  2606. if #self.path.way > max_len then
  2607. transition_state(self, "")
  2608. return
  2609. end
  2610. local wp = self.path.way[1]
  2611. if not wp then
  2612. transition_state(self, "")
  2613. return
  2614. end
  2615. -- Debug path display.
  2616. highlight_path(self)
  2617. local s = self.object:get_pos()
  2618. local dist = get_distance(wp, s)
  2619. -- Note: waypoint may be vertical from us (above or below).
  2620. if dist < 0.6 then
  2621. -- Reached waypoint, remove it from queue.
  2622. table.remove(self.path.way, 1)
  2623. self.path.waypoints_gotten = (self.path.waypoints_gotten or 0) + 1
  2624. -- Are we done following the path?
  2625. if #self.path.way == 0 then
  2626. pop_state(self)
  2627. return
  2628. end
  2629. -- Take shortcuts only if we've gotten a few waypoints successfully already.
  2630. -- The requirement that we must first traverse at least 4 waypoints prevents
  2631. -- rapid switching between the "main", "newpath", and "rondev" states.
  2632. -- Overall, taking shortcuts makes mob movement look a bit better, at the
  2633. -- cost that sometimes the mob walks into a trap and has to path out of it.
  2634. -- A 50/50 random number helps to break up circular traps.
  2635. local count = random(4, 8)
  2636. local fw = self.path.way[count]
  2637. if random(1, 2) == 1 and fw and abs(wp.y - fw.y) <= 2 and self.path.waypoints_gotten > 4 then
  2638. local y1 = self.object:get_yaw()
  2639. local y2 = yaw_to_pos(self, fw, s)
  2640. local d = yaw_delta(y1, y2)
  2641. if d > rad(20) then
  2642. -- Move raycast up a bit to improve behavior over rough terrain.
  2643. local a = {x=0, y=1, z=0}
  2644. if raycast_los(self, v_add(s, a), v_add(fw, a)) then
  2645. for i = 1, (count - 1), 1 do
  2646. table.remove(self.path.way, 1)
  2647. end
  2648. self.path.rondev_timeout = 5
  2649. transition_substate(self, "rondev")
  2650. end
  2651. end
  2652. end
  2653. elseif dist > 3 then -- Dist factor is a bit arbitrary right now.
  2654. -- We are some distance to the waypoint. Transition to the "rondev" state,
  2655. -- which tries to walk the mob to the target in a direct line.
  2656. self.path.rondev_timeout = 5
  2657. transition_substate(self, "rondev")
  2658. return
  2659. end
  2660. -- Is mob directly over or under the target?
  2661. -- If so, mob should move more slowly so we don't miss the waypoint.
  2662. local on_target = false
  2663. if abs(wp.x - s.x) < 0.2 and abs(wp.z - s.z) < 0.2 then
  2664. on_target = true
  2665. end
  2666. -- Note: the 'facing_wall_or_pit' function also checks for dangerous nodes.
  2667. -- But some dangerous nodes are non-walkable, which means the pathfinder
  2668. -- would path through them.
  2669. local path_careful = false
  2670. if not self.path.dangerous_paths then
  2671. if waypoint_dangerous(self, wp) then
  2672. -- Usually happens due to paths through deadly liquid.
  2673. transition_substate(self, "blocked")
  2674. return
  2675. elseif is_wall_or_pit(self, wp) then
  2676. -- This can happen if the environment changed (player dug pit or wall?).
  2677. self.path.blocked_count = self.path.blocked_count + 1
  2678. transition_substate(self, "blocked")
  2679. return
  2680. else
  2681. -- Soft "slowdown" check has to be performed last.
  2682. local result, reason = facing_wall_or_pit(self)
  2683. if result and (reason == "pit" or reason == "danger") then
  2684. -- Path goes in the direction of something dangerous, like a cliff.
  2685. -- But we don't care if the path is next to a wall.
  2686. path_careful = true
  2687. end
  2688. end
  2689. end
  2690. -- Query whether path is straight. Note: do this BEFORE rotating mob.
  2691. -- The mob's initial yaw is taken into account.
  2692. local sharp_turn = (not path_is_straight(self, s))
  2693. -- Get the mob facing in the right direction.
  2694. local yaw = yaw_to_pos(self, wp, s)
  2695. set_yaw(self, yaw)
  2696. -- Start moving to next waypoint.
  2697. if on_target then
  2698. -- Slow down so we don't overshoot waypoint.
  2699. set_velocity(self, 0.1)
  2700. set_animation(self, "walk", 5)
  2701. elseif path_careful then
  2702. -- Slow down when near dangerous terrain.
  2703. local half_run = ((self.walk_velocity or 0) + (self.run_velocity or 0)) / 2
  2704. set_velocity(self, half_run)
  2705. set_animation(self, "walk")
  2706. elseif sharp_turn then
  2707. -- Slow down to execute turns.
  2708. set_velocity(self, self.run_velocity or 0)
  2709. set_animation(self, "run")
  2710. else
  2711. set_velocity(self, self.sprint_velocity or 0)
  2712. set_animation(self, "run")
  2713. end
  2714. -- Jump only if next waypoint is higher than us.
  2715. if wp.y > s.y then
  2716. try_jump(self, dtime)
  2717. end
  2718. -- Is mob becoming stuck? (Haven't removed next waypoint in timely manner.)
  2719. -- Note that this can trigger if the mob just moves too slowly, so we should
  2720. -- avoid very-slow-moving behaviors when possible.
  2721. if self.stuck_timer > 3 then
  2722. self.path.blocked_count = self.path.blocked_count + 1
  2723. transition_substate(self, "blocked")
  2724. return
  2725. end
  2726. end
  2727. -- In this state, the mob is some distance from the first waypoint in the path,
  2728. -- and must move toward it in a direct line.
  2729. local function do_pathfind_rondev(self, dtime)
  2730. if not self.path.following or not self.path.way then
  2731. pop_state(self)
  2732. return
  2733. end
  2734. local wp = self.path.way[1]
  2735. if not wp then
  2736. pop_state(self)
  2737. return
  2738. end
  2739. -- If we've exceeded the time budget for this action, we must be blocked.
  2740. self.path.rondev_timeout = (self.path.rondev_timeout or 0) - dtime
  2741. if self.path.rondev_timeout < 0 then
  2742. self.path.blocked_count = self.path.blocked_count + 1
  2743. transition_substate(self, "blocked")
  2744. return
  2745. end
  2746. local s = self.object:get_pos()
  2747. -- Get the mob facing in the right direction.
  2748. local yaw = yaw_to_pos(self, wp, s)
  2749. set_yaw(self, yaw)
  2750. if facing_wall_or_pit(self) then
  2751. set_velocity(self, 0)
  2752. transition_substate(self, "newpath")
  2753. return
  2754. end
  2755. -- Slow down (half-run) to execute shortcuts.
  2756. set_velocity(self, self.run_velocity)
  2757. set_animation(self, "run")
  2758. try_jump(self, dtime)
  2759. if get_distance(wp, s) < 1.0 then
  2760. transition_substate(self, "")
  2761. return
  2762. end
  2763. end
  2764. local function try_unblock_path(self)
  2765. --report(self, "try unblock path")
  2766. local s = get_standing_pos(self)
  2767. local p = get_ahead_pos(self)
  2768. local w1 = self.path.way[1]
  2769. local w2 = self.path.way[2]
  2770. -- First, check if the waypoint is inside a walkable or dangerous node. This
  2771. -- would happen if the player (or another mob) modified the environment
  2772. -- through which the path traveled, by placing a block on it.
  2773. if w1 then
  2774. local nn = minetest.get_node(w1).name
  2775. local ndef = minetest.registered_nodes[nn]
  2776. if ndef.walkable or is_node_dangerous(self, nn, ndef) then
  2777. --report(self, "floating in: " .. nn)
  2778. if try_break_block(self, w1) then
  2779. return "continue"
  2780. elseif try_place_block(self, v_add(w1, {x=0, y=1, z=0})) then
  2781. -- Jump up to avoid getting stuck in placed node.
  2782. if w1.y + 1 >= p.y then
  2783. force_jump_up(self, 1)
  2784. end
  2785. -- Move waypoint 2 nodes up and try to continue the same path.
  2786. w1.y = w1.y + 2
  2787. return "continue"
  2788. else
  2789. return ""
  2790. end
  2791. end
  2792. end
  2793. -- Check if the waypoint floating OVER non-walkable (like air). For example,
  2794. -- player might have dug a pit in the mob's path.
  2795. do
  2796. local p2 = v_add(w1, {x=0, y=-1, z=0})
  2797. local nn = minetest.get_node(p2).name
  2798. local ndef = minetest.registered_nodes[nn]
  2799. if not ndef.walkable or is_node_dangerous(self, nn, ndef) then
  2800. report(self, "floating over")
  2801. if try_place_block(self, p2) then
  2802. -- Waypoint goes over placed block; path not modified.
  2803. return "continue"
  2804. elseif try_place_block(self, w1) then
  2805. return "newpath"
  2806. else
  2807. return ""
  2808. end
  2809. end
  2810. end
  2811. -- Is path obstructed by a mob or player?
  2812. if w1 then
  2813. -- Note: w1 is the obstructed waypoint, w2 is the waypoint beyond.
  2814. local obstructed = false
  2815. local can_move = false
  2816. -- Check both the next waypoint AND the mob's "ahead" pos. They might be
  2817. -- separated by some distance, and thus one might be blocked while the other
  2818. -- is not.
  2819. local objs = get_targets_in_radius(self, w1, 1.5)
  2820. if #objs > 0 then
  2821. obstructed = true
  2822. else
  2823. objs = get_targets_in_radius(self, p, 1.5)
  2824. if #objs > 0 then obstructed = true end
  2825. end
  2826. -- Make sure nothing is obstructing the mob (assuming 2-node high mob).
  2827. if obstructed then
  2828. local p2 = v_add(w1, {x=0, y=1, z=0})
  2829. if try_break_block(self, p2) then
  2830. can_move = true
  2831. end
  2832. end
  2833. if obstructed and can_move then
  2834. -- If obstructed, I can deal with this by simply moving the mob by fiat.
  2835. -- Note: cannot use move_to(), it simply collides.
  2836. local t = vector.copy(w1)
  2837. t.y = (t.y - 0.5) + abs(self.collisionbox[2])
  2838. self.object:set_pos(t) -- Place mob exactly on ground.
  2839. -- Remove waypoint.
  2840. table.remove(self.path.way, 1)
  2841. return "continue"
  2842. end
  2843. end
  2844. -- Path goes over a hump while ceiling prevents jumping.
  2845. -- (This function doesn't check for a ceiling, but we assume there is one,
  2846. -- otherwise the movement code would have just jumped over the hump.)
  2847. if w1 and w1.y == p.y + 1 then
  2848. if w2 and w2.y <= w1.y then
  2849. local result, reason = try_break_block(self, p)
  2850. if result then
  2851. -- Modify path slightly.
  2852. w1.y = w1.y - 1
  2853. return "continue"
  2854. else
  2855. -- Couldn't remove blockage (protected, unbreakable, etc.).
  2856. -- Try something else.
  2857. if try_place_block(self, w1) then
  2858. return "newpath"
  2859. end
  2860. end
  2861. end
  2862. end
  2863. -- Path's next waypoint is 2 nodes or higher from mob's ahead position.
  2864. -- Most mobs can't jump this high (neither can the player, usually).
  2865. if w1 and w1.y > p.y + 1 then
  2866. local p2 = v_add(w1, {x=0, y=-1, z=0})
  2867. local result, reason = try_break_block(self, p2)
  2868. if result then
  2869. -- Modify path slightly.
  2870. w1.y = w1.y - 1
  2871. return "continue"
  2872. else
  2873. -- Couldn't remove blockage (protected, unbreakable, etc.).
  2874. -- Try something else.
  2875. if try_place_block(self, w1) then
  2876. return "newpath"
  2877. end
  2878. end
  2879. end
  2880. -- Path goes straight ahead flat (or down). Mob is probably blocked by
  2881. -- blockage over a 1x1 hole or other space too low to fit its head through.
  2882. if w1 and w1.y <= p.y then
  2883. local p2 = v_add(p, {x=0, y=1, z=0})
  2884. local result, reason = try_break_block(self, p2)
  2885. if result then
  2886. -- Keep following path unmodified.
  2887. return "continue"
  2888. else
  2889. -- Couldn't remove blockage (protected, unbreakable, etc.).
  2890. -- Try something else.
  2891. if try_place_block(self, w1) then
  2892. return "newpath"
  2893. end
  2894. end
  2895. end
  2896. -- Path goes up stairs. In this case, we DON'T want to dig the stair node.
  2897. -- We have to dig the ceiling instead.
  2898. if w1 and w2 and w1.y > p.y and w2.y > w1.y then
  2899. local p2 = get_standing_pos(self)
  2900. p2.y = p2.y + 2
  2901. local result, reason = try_break_block(self, p2)
  2902. if result then
  2903. -- Keep following path.
  2904. return "continue"
  2905. else
  2906. -- Couldn't remove ceiling blockage (protected, unbreakable, etc.).
  2907. -- Try something else.
  2908. if try_place_block(self, w1) then
  2909. return "newpath"
  2910. end
  2911. end
  2912. end
  2913. return ""
  2914. end
  2915. -- This pathfinding state attempts to remove (or place) blocks in order to get
  2916. -- around blockages. It should only be entered if the mob's pathfinding value is
  2917. -- 2 or greater.
  2918. local function do_pathfind_blocked(self, dtime)
  2919. -- Usually, mob should be facing whatever is blocking us. Generally, only
  2920. -- other entities (like mobs) and physical terrain are responsible for this.
  2921. if not self.path.following or not self.path.way then
  2922. transition_state(self, "")
  2923. return
  2924. end
  2925. -- Blocked too many times without successful unblocking? Give up.
  2926. if self.path.blocked_count > 3 then
  2927. transition_state(self, "")
  2928. return
  2929. end
  2930. -- Mob does not support this level of pathfinding?
  2931. if (self.pathfinding or 0) < 2 then
  2932. transition_state(self, "")
  2933. return
  2934. end
  2935. local wp = self.path.way[1]
  2936. if not wp then
  2937. transition_state(self, "")
  2938. return
  2939. end
  2940. -- Halt mob's movement while we try to unblock the path.
  2941. set_velocity(self, 0)
  2942. set_animation(self, "stand")
  2943. -- Get mob facing the next waypoint (and the blockage, presumably).
  2944. local yaw = yaw_to_pos(self, wp, self.object:get_pos())
  2945. set_yaw(self, yaw)
  2946. -- Limit the rate at which blockage is removed.
  2947. self.path.blocked_timer = (self.path.blocked_timer or 0) + dtime
  2948. if self.path.blocked_timer > 1 then
  2949. self.path.blocked_timer = 0
  2950. local result = try_unblock_path(self)
  2951. if result == "continue" then
  2952. -- Continue original path. (Note: path might have been modified slightly.)
  2953. self.path.blocked_count = 0
  2954. transition_substate(self, "")
  2955. return
  2956. elseif result == "newpath" then
  2957. -- The attempt resulted in the environment being changed; retry pathfinder.
  2958. self.path.blocked_count = 0
  2959. transition_substate(self, "newpath")
  2960. return
  2961. else
  2962. -- Couldn't remove blockage.
  2963. pop_state(self)
  2964. return
  2965. end
  2966. end
  2967. end
  2968. local function do_pathfind_exit(self)
  2969. self.path.following = false
  2970. self.path.way = nil
  2971. self.path.dangerous_paths = false
  2972. end
  2973. -- Pillar and tunnel to get to the target.
  2974. local function do_digbuild_state(self, dtime)
  2975. -- Pathfinder does not have a target?
  2976. if not self.digbuild.target then
  2977. transition_state(self, "")
  2978. return
  2979. end
  2980. -- Mob does not support this level of pathfinding?
  2981. if (self.pathfinding or 0) < 3 then
  2982. transition_state(self, "")
  2983. return
  2984. end
  2985. -- Has mob reached its objective?
  2986. if v_distance(self.object:get_pos(), self.digbuild.target) < 1 then
  2987. pop_state(self)
  2988. return
  2989. end
  2990. local s = self.object:get_pos()
  2991. local p = self.digbuild.target
  2992. local yaw = yaw_to_pos(self, p, s)
  2993. set_yaw(self, yaw)
  2994. -- Start moving! The goal is to get as close to the target as possible in the
  2995. -- X,Z plane before we go up or down.
  2996. local face_result, face_reason = facing_wall_or_pit(self)
  2997. -- If the mob is over or under the target, slow down.
  2998. local overunder = false
  2999. if abs(s.x - p.x) < 0.5 and abs(s.z - p.z) < 0.5 then
  3000. velocity = self.walk_velocity or 0
  3001. overunder = true
  3002. elseif abs(s.x - p.x) < 0.2 and abs(s.z - p.z) < 0.2 then
  3003. overunder = true
  3004. velocity = 0.1
  3005. end
  3006. if face_result or overunder then
  3007. set_velocity(self, 0)
  3008. set_animation(self, "stand")
  3009. else
  3010. -- Get mob moving in the right direction.
  3011. local velocity = self.run_velocity or 0
  3012. set_velocity(self, velocity)
  3013. set_animation(self, "run")
  3014. try_jump(self, dtime)
  3015. return
  3016. end
  3017. -- Another function handles the obstacle we (hopefully) just ran into.
  3018. if face_reason == "wall" or face_reason == "pit" or overunder then
  3019. transition_substate(self, "obstacle")
  3020. return
  3021. end
  3022. if self.stand_timer > 1 then
  3023. transition_substate(self, "obstacle")
  3024. return
  3025. end
  3026. end
  3027. -- Dig up until we reach the top of a wall.
  3028. local function do_digbuild_pillar(self, dtime)
  3029. -- Do nothing until mob is centered in column. Otherwise might get stuck!
  3030. if keep_mob_centered(self) then
  3031. return
  3032. end
  3033. local s = self.object:get_pos()
  3034. local p = self.digbuild.target
  3035. local v = self.object:get_velocity()
  3036. -- Get mob facing in the right direction.
  3037. local yaw = yaw_to_pos(self, p, s)
  3038. set_yaw(self, yaw)
  3039. set_velocity(self, 0)
  3040. -- Limit upward building to once per second.
  3041. self.digbuild.node_timer = self.digbuild.node_timer + dtime
  3042. if self.digbuild.node_timer > 0.5 then
  3043. set_animation(self, "stand")
  3044. end
  3045. if self.digbuild.node_timer < 1 then return end
  3046. self.digbuild.node_timer = 0
  3047. -- Obviosly we can't pillar if the mob is currently falling. We check this
  3048. -- only after checking the dig/build timer, otherwise it would run every frame
  3049. -- and we would immediately exit the pillaring function on every upward jump.
  3050. if v.y < 0 then
  3051. transition_state(self, "")
  3052. return
  3053. end
  3054. -- Ceiling position. Assume mob is 2 blocks high, so it digs above its
  3055. -- head. Position is rounded, so we use a fixed integer.
  3056. local sps = get_standing_pos(self)
  3057. local cps = v_add(sps, {x=0, y=2, z=0})
  3058. -- Cancel pillaring if we're above or near the target's X,Z level.
  3059. if sps.y >= self.digbuild.target.y then
  3060. transition_substate(self, "")
  3061. return
  3062. end
  3063. -- Try to dig ceiling first, then place floor block. There is no point in
  3064. -- placing the floor block unless we can dig the ceiling. Otherwise mob would
  3065. -- just get stuck.
  3066. if try_break_block(self, cps) then
  3067. if try_place_block(self, sps) then
  3068. set_animation(self, "punch")
  3069. force_jump_up(self, 1)
  3070. -- If we reach a plateau, we might be able to path from here.
  3071. local decks = walkable_around(sps)
  3072. if #decks > 1 then -- Always at least 1 due to self.
  3073. -- Try swapping back to the pathfinder.
  3074. -- Note: we assume that if the pathfinder cannot find a path, that it
  3075. -- does NOT move the mob!
  3076. self.path.target = self.digbuild.target
  3077. pop_state(self)
  3078. push_state(self, "pathfind")
  3079. return
  3080. end
  3081. -- If we are above our target, we should switch to bridge/tunnel.
  3082. if sps.y >= self.digbuild.target.y then
  3083. transition_substate(self, "tunnel")
  3084. return
  3085. end
  3086. else
  3087. -- Cannot build, stop trying to get target.
  3088. transition_state(self, "")
  3089. return
  3090. end
  3091. else
  3092. -- Cannot dig, stop trying to get target.
  3093. transition_state(self, "")
  3094. return
  3095. end
  3096. end
  3097. local function do_digbuild_dig(self, dtime)
  3098. -- Do nothing until mob is centered in column. Otherwise might get stuck!
  3099. if keep_mob_centered(self) then
  3100. return
  3101. end
  3102. local s = self.object:get_pos()
  3103. local p = self.digbuild.target
  3104. -- Get mob facing in the right direction.
  3105. local yaw = yaw_to_pos(self, p, s)
  3106. set_yaw(self, yaw)
  3107. set_velocity(self, 0)
  3108. -- Limit downward building to once per second.
  3109. self.digbuild.node_timer = self.digbuild.node_timer + dtime
  3110. if self.digbuild.node_timer > 0.5 then
  3111. set_animation(self, "stand")
  3112. end
  3113. if self.digbuild.node_timer < 1 then return end
  3114. self.digbuild.node_timer = 0
  3115. -- Ground position.
  3116. local sps = get_standing_pos(self)
  3117. local fps = v_add(sps, {x=0, y=-1, z=0})
  3118. local ups = v_add(sps, {x=0, y=-2, z=0})
  3119. -- Cancel digging if we're below or near the target's X,Z level.
  3120. if sps.y <= self.digbuild.target.y then
  3121. transition_substate(self, "")
  3122. return
  3123. end
  3124. -- Don't dig block below if mob would fall.
  3125. if not pos_walkable(ups) then
  3126. transition_state(self, "")
  3127. return
  3128. end
  3129. if try_break_block(self, fps) then
  3130. set_animation(self, "punch")
  3131. -- If we reach a plateau, we might be able to path from here.
  3132. local decks = walkable_around(v_add(fps, {x=0, y=-1, z=0}))
  3133. if #decks > 1 then -- Always at least 1 due to self.
  3134. -- Try swapping back to the pathfinder.
  3135. -- Note: we assume that if the pathfinder cannot find a path, that it
  3136. -- does NOT move the mob!
  3137. self.path.target = self.digbuild.target
  3138. pop_state(self)
  3139. push_state(self, "pathfind")
  3140. return
  3141. end
  3142. -- If we are below our target, we should switch to bridge/tunnel.
  3143. if sps.y <= self.digbuild.target.y then
  3144. transition_substate(self, "tunnel")
  3145. return
  3146. end
  3147. else
  3148. -- Cannot dig, stop trying to get target.
  3149. transition_state(self, "")
  3150. return
  3151. end
  3152. end
  3153. local function do_digbuild_tunnel(self, dtime)
  3154. -- Do nothing until mob is centered in column. Otherwise might get stuck!
  3155. if keep_mob_centered(self) then
  3156. return
  3157. end
  3158. -- Exit if falling.
  3159. local v = self.object:get_velocity()
  3160. if v.y < 0 then
  3161. transition_state(self, "")
  3162. return
  3163. end
  3164. local s = self.object:get_pos()
  3165. local p = self.digbuild.target
  3166. -- Get mob facing in the right direction.
  3167. local yaw = yaw_to_pos(self, p, s)
  3168. set_yaw(self, yaw)
  3169. set_velocity(self, 0)
  3170. --local face_result, face_reason = facing_wall_or_pit(self)
  3171. -- If we're no longer facing a wall or other obstacle, we can stop
  3172. -- tunneling/bridging operations (for now).
  3173. --if face_reason == "surface" then
  3174. -- transition_substate(self, "")
  3175. -- return
  3176. --end
  3177. -- Face one of the cardinal directions, and if that direction is a surface,
  3178. -- move to it.
  3179. set_yaw(self, square_yaw(yaw))
  3180. local face_result, face_reason = facing_wall_or_pit(self)
  3181. if face_reason == "surface" then
  3182. self.digbuild.move_to = get_ahead_pos(self)
  3183. transition_substate(self, "move")
  3184. return
  3185. end
  3186. -- Limit digging/building to once per second.
  3187. self.digbuild.node_timer = self.digbuild.node_timer + dtime
  3188. if self.digbuild.node_timer > 0.5 then
  3189. set_animation(self, "stand")
  3190. end
  3191. if self.digbuild.node_timer < 1 then return end
  3192. self.digbuild.node_timer = 0
  3193. -- Tunnel/bridge position. Assume mob is 2 blocks high, so it digs blocks for
  3194. -- its head. Position is rounded, so we use a fixed integer.
  3195. local p1 = get_ahead_pos(self)
  3196. local p2 = v_add(p1, {x=0, y=1, z=0})
  3197. local p0 = v_add(p1, {x=0, y=-1, z=0})
  3198. -- Place bridge block if needed.
  3199. if not pos_walkable(p0) then
  3200. try_place_block(self, p0, true)
  3201. end
  3202. -- Try digging the doorway.
  3203. if try_break_block(self, p1) then
  3204. if try_break_block(self, p2) then
  3205. -- Both blocks facing forwards are successfully dug (or didn't exist).
  3206. -- If we reach an opening, we might be able to path from here.
  3207. -- Start with at least 2 due to self + path behind us.
  3208. local amount = 2
  3209. local decks = walkable_around(p0)
  3210. if #decks <= 2 then
  3211. -- In this case there shouldn't be more than 1 if there is no opening.
  3212. decks = walkable_around(p1)
  3213. amount = 1
  3214. end
  3215. if #decks > amount then
  3216. -- Try swapping back to the pathfinder.
  3217. -- Note: we assume that if the pathfinder cannot find a path, that it
  3218. -- does NOT move the mob!
  3219. self.path.target = self.digbuild.target
  3220. pop_state(self)
  3221. push_state(self, "pathfind")
  3222. return
  3223. end
  3224. -- Move to the section we just built/dug.
  3225. self.digbuild.move_to = p1
  3226. self.digbuild.node_timer = 1
  3227. transition_substate(self, "move")
  3228. else
  3229. -- Cannot dig, stop trying to get target.
  3230. transition_state(self, "")
  3231. return
  3232. end
  3233. else
  3234. -- Cannot dig, stop trying to get target.
  3235. transition_state(self, "")
  3236. return
  3237. end
  3238. end
  3239. -- Move the mob to the target location. We assume the distance to this location
  3240. -- is no more than 1.5 nodes, more or less, and that there are NO obstacles.
  3241. -- Once we've reached the target, we transition to the primary state.
  3242. local function do_digbuild_move(self, dtime)
  3243. if not self.digbuild.move_to then
  3244. transition_state(self, "")
  3245. return
  3246. end
  3247. local s = self.object:get_pos()
  3248. local c = self.digbuild.move_to
  3249. -- Abort if stuck.
  3250. if self.stuck_timer > 5 then
  3251. transition_state(self, "")
  3252. return
  3253. end
  3254. -- Walk to target.
  3255. if abs(s.x - c.x) > 0.4 or abs(s.z - c.z) > 0.4 then
  3256. set_yaw(self, yaw_to_pos(self, c, s))
  3257. set_velocity(self, self.walk_velocity or 0)
  3258. try_jump(self, dtime)
  3259. set_animation(self, "walk")
  3260. return
  3261. end
  3262. transition_substate(self, "")
  3263. end
  3264. -- This function expects that the mob is currently facing an obstacle, and NOT
  3265. -- currently moving.
  3266. local function do_digbuild_obstacle(self, dtime)
  3267. if keep_mob_centered(self) then
  3268. return
  3269. end
  3270. -- First, square the mob's yaw so we can accurately get the obstacle type.
  3271. set_velocity(self, 0)
  3272. set_yaw(self, square_yaw(self.object:get_yaw()))
  3273. -- Wait a moment. (Note: timer only increments when mob is standing still!)
  3274. --if self.stand_timer < 1 then
  3275. -- report(self, "waiting ...")
  3276. -- return
  3277. --end
  3278. local face_result, face_reason = facing_wall_or_pit(self)
  3279. local s = self.object:get_pos()
  3280. local p = self.digbuild.target
  3281. -- Is target directly over or under us?
  3282. if abs(p.x - s.x) < 0.3 and abs(p.z - s.z) < 0.3 then
  3283. if s.y < (p.y - 0.9) then
  3284. transition_substate(self, "pillar")
  3285. return
  3286. elseif s.y > (p.y + 0.9) then
  3287. transition_substate(self, "dig")
  3288. return
  3289. else
  3290. -- We have reached the target.
  3291. pop_state(self)
  3292. return
  3293. end
  3294. -- Is target more than 1 block higher, and we are facing a wall or pit?
  3295. elseif p.y >= (s.y + 0.9) then
  3296. if face_reason == "wall" then
  3297. transition_substate(self, "pillar")
  3298. return
  3299. elseif face_reason == "pit" then
  3300. transition_substate(self, "tunnel")
  3301. return
  3302. elseif face_reason == "surface" then
  3303. self.digbuild.move_to = get_ahead_pos(self)
  3304. transition_substate(self, "move")
  3305. return
  3306. else
  3307. transition_state(self, "")
  3308. return
  3309. end
  3310. -- Otherwise, is target more than 1 block lower than us?
  3311. elseif p.y < (s.y - 0.9) then
  3312. if face_reason == "pit" then
  3313. transition_substate(self, "dig")
  3314. return
  3315. elseif face_reason == "wall" then
  3316. transition_substate(self, "tunnel")
  3317. return
  3318. elseif face_reason == "surface" then
  3319. self.digbuild.move_to = get_ahead_pos(self)
  3320. transition_substate(self, "move")
  3321. return
  3322. else
  3323. transition_state(self, "")
  3324. return
  3325. end
  3326. -- Otherwise, we are (nearly) on the same level as the target.
  3327. else
  3328. -- Dig tunnel through rock, or build bridge through air.
  3329. if face_reason == "pit" or face_reason == "wall" then
  3330. transition_substate(self, "tunnel")
  3331. return
  3332. elseif face_reason == "surface" then
  3333. self.digbuild.move_to = get_ahead_pos(self)
  3334. transition_substate(self, "move")
  3335. return
  3336. end
  3337. end
  3338. -- Encountered a situation we don't know how to deal with. Cancel.
  3339. transition_state(self, "")
  3340. end
  3341. local function do_follow_state(self, dtime)
  3342. if not self.following then
  3343. transition_state(self, "")
  3344. return
  3345. end
  3346. local s = self.object:get_pos()
  3347. local p = self.following:get_pos()
  3348. -- Stop following if target doesn't exist anymore.
  3349. if not p then
  3350. transition_state(self, "")
  3351. return
  3352. end
  3353. -- Stop following when (...) (who comes up with these terms? Geez).
  3354. if self.horny then
  3355. transition_state(self, "")
  3356. return
  3357. end
  3358. -- Avoid dangerous nodes.
  3359. if is_node_dangerous(self, self.standing_in) then
  3360. push_state(self, "avoid")
  3361. return
  3362. end
  3363. -- Stop following if no longer holding item the (non-NPC) mob wants. Does not
  3364. -- apply to NPCs.
  3365. if self.type ~= "npc" then
  3366. if not follow_holding(self, self.following) then
  3367. transition_state(self, "")
  3368. return
  3369. end
  3370. end
  3371. -- Follow that thing!
  3372. local yaw = yaw_to_pos(self, p, s)
  3373. set_yaw(self, yaw, 6)
  3374. if v_distance(s, p) > self.reach then
  3375. set_velocity(self, self.walk_velocity or 0)
  3376. set_animation(self, "walk")
  3377. try_jump(self, dtime)
  3378. else
  3379. set_velocity(self, 0)
  3380. set_animation(self, "stand")
  3381. end
  3382. -- If stuck, maybe we can pathfind to target.
  3383. if self.stuck_timer > 5 then
  3384. if (self.pathfinding or 0) >= 1 then
  3385. self.path.target = v_round(p)
  3386. push_state(self, "pathfind")
  3387. return
  3388. else
  3389. transition_state(self, "")
  3390. return
  3391. end
  3392. end
  3393. end
  3394. local function do_follow_exit(self)
  3395. self.following = nil
  3396. end
  3397. -- This table contains all the individual state functions and their transitions.
  3398. local state_machine = {
  3399. -- State with no name.
  3400. [""] = {
  3401. enter = do_stand_enter,
  3402. main = do_stand_state,
  3403. },
  3404. stand = {
  3405. enter = do_stand_enter,
  3406. main = do_stand_state,
  3407. },
  3408. walk = {
  3409. enter = do_walk_enter,
  3410. main = do_walk_state,
  3411. },
  3412. avoid = {
  3413. enter = do_avoid_enter,
  3414. main = do_avoid_state,
  3415. },
  3416. runaway = {
  3417. enter = do_runaway_enter,
  3418. main = do_runaway_state,
  3419. continuous = true,
  3420. },
  3421. attack = {
  3422. enter = do_attack_enter,
  3423. exit = do_attack_exit,
  3424. main = do_attack_state,
  3425. chase = do_chase_attack,
  3426. shoot = do_shoot_attack,
  3427. caught = do_caught_attack,
  3428. blocked = do_blocked_attack,
  3429. continuous = true,
  3430. },
  3431. pathfind = {
  3432. enter = do_pathfind_enter,
  3433. main = do_pathfind_state,
  3434. blocked = do_pathfind_blocked,
  3435. newpath = do_pathfind_newpath,
  3436. rondev = do_pathfind_rondev,
  3437. exit = do_pathfind_exit,
  3438. continuous = true,
  3439. },
  3440. digbuild = {
  3441. main = do_digbuild_state,
  3442. pillar = do_digbuild_pillar,
  3443. dig = do_digbuild_dig,
  3444. tunnel = do_digbuild_tunnel,
  3445. move = do_digbuild_move,
  3446. obstacle = do_digbuild_obstacle,
  3447. continuous = true,
  3448. },
  3449. follow = {
  3450. main = do_follow_state,
  3451. exit = do_follow_exit,
  3452. },
  3453. }
  3454. -- Export.
  3455. mobs.state_machine = state_machine
  3456. -- Execute current state (stand, walk, run, attacks). This function is rate
  3457. -- limited to reduce server load; thus 'dtime' may be large, but should usually
  3458. -- be within 1 second. [MustTest]
  3459. local function do_states(self, dtime)
  3460. -- Stupid spurious bugs [MustTest]. Implies our object no longer exists.
  3461. local yaw = self.object:get_yaw()
  3462. if not yaw then return end
  3463. -- Deal with invalid states. Note: unknown state types (non-empty string) are
  3464. -- valid and we don't do anything with them; they can be used by some mobs.
  3465. if not self.state or self.state == "" then
  3466. transition_state(self, "stand")
  3467. end
  3468. --report(self, "current state: " .. self.state .. " (" .. self.substate .. ")", 2)
  3469. -- Execute current state's main function.
  3470. local sm = mobs.state_machine
  3471. local state = sm[self.state]
  3472. if state[self.substate] then
  3473. state[self.substate](self, dtime)
  3474. elseif state.main then
  3475. state.main(self, dtime)
  3476. end
  3477. end
  3478. -- Export.
  3479. mobs.do_states = function(...)
  3480. do_states(...)
  3481. end
  3482. -- falling and fall damage
  3483. local function falling(self, pos)
  3484. if self.fly then
  3485. return
  3486. end
  3487. -- floating in water (or falling)
  3488. local v = self.object:get_velocity()
  3489. if v.y > 0 then
  3490. -- apply gravity when moving up
  3491. self.object:set_acceleration({
  3492. x = 0,
  3493. y = -10,
  3494. z = 0
  3495. })
  3496. elseif v.y <= 0 and v.y > self.fall_speed then
  3497. -- fall downwards at set speed
  3498. self.object:set_acceleration({
  3499. x = 0,
  3500. y = self.fall_speed,
  3501. z = 0
  3502. })
  3503. else
  3504. -- stop accelerating once max fall speed hit
  3505. self.object:set_acceleration({x = 0, y = 0, z = 0})
  3506. end
  3507. -- If in water then float up. Nil check.
  3508. local ndef = self.standing_in and minetest.reg_ns_nodes[self.standing_in]
  3509. if ndef and ndef.groups.water then
  3510. if self.floats == 1 then
  3511. self.object:set_acceleration({
  3512. x = 0,
  3513. y = -self.fall_speed / (max(1, v.y) ^ 8), -- 8 was 2
  3514. z = 0
  3515. })
  3516. end
  3517. else
  3518. -- fall damage onto solid ground
  3519. if self.fall_damage == 1
  3520. and self.object:get_velocity().y == 0 then
  3521. local d = (self.old_y or 0) - self.object:get_pos().y
  3522. if d > 5 then
  3523. self.health = self.health - floor(d - 5)
  3524. effect(pos, 5, "tnt_smoke.png", 1, 2, 2, nil)
  3525. if check_for_death(self, "fall", {type = "fall"}) then
  3526. return
  3527. end
  3528. end
  3529. self.old_y = self.object:get_pos().y
  3530. end
  3531. end
  3532. end
  3533. -- is Took Ranks mod active?
  3534. local tr = minetest.get_modpath("toolranks")
  3535. -- Deal damage and effects when mob punched.
  3536. local function mob_punch(self, hitter, tflp, tool_capabilities, dir)
  3537. -- Mob health check.
  3538. if self.health <= 0 then return end
  3539. -- Sanity check.
  3540. if not tool_capabilities then return end
  3541. -- Custom punch function.
  3542. if self.do_punch then
  3543. -- When false skip going any further.
  3544. if self.do_punch(self, hitter, tflp, tool_capabilities, dir) == false then
  3545. return
  3546. end
  3547. end
  3548. -- Record name of last attacker.
  3549. self.last_attacked_by = (hitter and hitter:is_player() and hitter:get_player_name()) or ""
  3550. -- Is mob protected?
  3551. if self.protected and hitter:is_player()
  3552. and minetest.test_protection(v_round(self.object:get_pos()), hitter:get_player_name()) then
  3553. minetest.chat_send_player(hitter:get_player_name(), "# Server: Mob has been protected!")
  3554. return
  3555. end
  3556. -- weapon wear
  3557. local weapon = hitter:get_wielded_item()
  3558. --minetest.log("weapon: <" .. weapon:get_name() .. ">")
  3559. local punch_interval = 1.4
  3560. -- calculate mob damage
  3561. local damage = 0
  3562. local armor = self.object:get_armor_groups() or {}
  3563. local tmp
  3564. -- quick error check incase it ends up 0 (serialize.h check test)
  3565. if tflp == 0 then
  3566. tflp = 0.2
  3567. end
  3568. do
  3569. for group,_ in pairs( (tool_capabilities.damage_groups or {}) ) do
  3570. tmp = tflp / (tool_capabilities.full_punch_interval or 1.4)
  3571. if tmp < 0 then
  3572. tmp = 0.0
  3573. elseif tmp > 1 then
  3574. tmp = 1.0
  3575. end
  3576. damage = damage + (tool_capabilities.damage_groups[group] or 0)
  3577. * tmp * ((armor[group] or 0) / 100.0)
  3578. end
  3579. end
  3580. -- check for tool immunity or special damage
  3581. for n = 1, #self.immune_to do
  3582. if self.immune_to[n][1] == weapon:get_name() then
  3583. damage = self.immune_to[n][2] or 0
  3584. break
  3585. -- if "all" then no tool does damage unless it's specified in list
  3586. elseif self.immune_to[n][1] == "all" then
  3587. damage = self.immune_to[n][2] or 0
  3588. end
  3589. end
  3590. -- healing
  3591. if damage <= -1 then
  3592. self.health = self.health - floor(damage)
  3593. return
  3594. end
  3595. -- add weapon wear
  3596. if tool_capabilities then
  3597. punch_interval = tool_capabilities.full_punch_interval or 1.4
  3598. end
  3599. if weapon:get_definition()
  3600. and weapon:get_definition().tool_capabilities then
  3601. -- toolrank support
  3602. local wear = floor((punch_interval / 75) * 9000)
  3603. if mobs.is_creative(hitter:get_player_name()) then
  3604. if tr then
  3605. wear = 1
  3606. else
  3607. wear = 0
  3608. end
  3609. end
  3610. if tr then
  3611. if weapon:get_definition()
  3612. and weapon:get_definition().original_description then
  3613. weapon:add_wear(toolranks.new_afteruse(weapon, hitter, nil, {wear = wear}))
  3614. end
  3615. else
  3616. weapon:add_wear(wear)
  3617. end
  3618. hitter:set_wielded_item(weapon)
  3619. end
  3620. -- only play hit sound and show blood effects if damage is 1 or over
  3621. if damage >= 1 then
  3622. -- weapon sounds
  3623. if weapon:get_definition().sounds ~= nil then
  3624. local s = random(0, #weapon:get_definition().sounds)
  3625. minetest.sound_play(weapon:get_definition().sounds[s], {
  3626. object = self.object, --hitter,
  3627. max_hear_distance = 20
  3628. }, true)
  3629. else
  3630. minetest.sound_play("default_punch", {
  3631. object = self.object, --hitter,
  3632. max_hear_distance = 20
  3633. }, true)
  3634. end
  3635. -- blood_particles
  3636. if self.blood_amount > 0 and not disable_blood then
  3637. local pos = self.object:get_pos()
  3638. pos.y = pos.y + (-self.collisionbox[2] + self.collisionbox[5]) * .5
  3639. -- do we have a single blood texture or multiple?
  3640. if type(self.blood_texture) == "table" then
  3641. local blood = self.blood_texture[random(1, #self.blood_texture)]
  3642. effect(pos, self.blood_amount, blood, nil, nil, 1, nil)
  3643. else
  3644. effect(pos, self.blood_amount, self.blood_texture, nil, nil, 1, nil)
  3645. end
  3646. end
  3647. -- do damage
  3648. self.health = self.health - floor(damage)
  3649. -- exit here if dead, special item check
  3650. if weapon:get_name() == "mobs:pick_lava" then
  3651. if check_for_death(self, "lava", {
  3652. type = "punch",
  3653. puncher = hitter,
  3654. tool_capabilities = tool_capabilities,
  3655. wielded = weapon,
  3656. }) then
  3657. return
  3658. end
  3659. else
  3660. if check_for_death(self, "hit", {
  3661. type = "punch",
  3662. puncher = hitter,
  3663. tool_capabilities = tool_capabilities,
  3664. wielded = weapon,
  3665. }) then
  3666. return
  3667. end
  3668. end
  3669. --[[ add healthy afterglow when hit (can cause hit lag with larger textures)
  3670. minetest.after(0.1, function()
  3671. if not self.object:get_luaentity() then return end
  3672. self.object:settexturemod("^[colorize:#c9900070")
  3673. core.after(0.3, function()
  3674. self.object:settexturemod("")
  3675. end)
  3676. end) ]]
  3677. -- knock back effect (only on full punch)
  3678. if self.knock_back and tflp >= punch_interval then
  3679. local v = self.object:get_velocity()
  3680. local r = 1.4 - min(punch_interval, 1.4)
  3681. local kb = r * 5
  3682. local up = 2
  3683. -- if already in air then dont go up anymore when hit
  3684. if v.y > 0
  3685. or self.fly then
  3686. up = 0
  3687. end
  3688. -- direction error check
  3689. dir = dir or {x = 0, y = 0, z = 0}
  3690. -- check if tool already has specific knockback value
  3691. if tool_capabilities.damage_groups["knockback"] then
  3692. kb = tool_capabilities.damage_groups["knockback"]
  3693. else
  3694. kb = kb * default_knockback
  3695. end
  3696. self.object:set_velocity({
  3697. x = dir.x * kb,
  3698. y = up,
  3699. z = dir.z * kb
  3700. })
  3701. self.pause_timer = 0.25
  3702. end
  3703. end -- END if damage
  3704. -- If skittish then run away.
  3705. if self.runaway == true then
  3706. local lp = hitter:get_pos()
  3707. local s = self.object:get_pos()
  3708. local yaw = yaw_to_pos(self, lp, s)
  3709. yaw = yaw + pi -- go in reverse
  3710. yaw = set_yaw(self, yaw, 6)
  3711. transition_state(self, "runaway")
  3712. return
  3713. end
  3714. -- Ignore punches from self.
  3715. if self.object == hitter then return end
  3716. -- Ignore punches if mob is passive.
  3717. if self.passive then return end
  3718. if self.child then return end
  3719. -- Ignore punches from owner.
  3720. local name = (hitter:is_player() and hitter:get_player_name()) or ""
  3721. if name ~= "" and name == self.owner then
  3722. return
  3723. end
  3724. -- Note: mob can defend itself if punched by invisible players, so no
  3725. -- invisibility check here.
  3726. -- Attack whoever punched mob (if not already attacking that player/mob).
  3727. if self.state ~= "attack" or self.attack ~= hitter then
  3728. transition_state(self, "")
  3729. do_attack(self, hitter)
  3730. end
  3731. if not self.group_attack then return end
  3732. -- Alert others to the attack.
  3733. local objs = minetest.get_objects_inside_radius(hitter:get_pos(), self.view_range)
  3734. for n = 1, #objs, 1 do
  3735. local obj = objs[n]:get_luaentity()
  3736. if obj and obj._cmi_is_mob then
  3737. -- Alert members of same mob if have 'group_attack'.
  3738. if obj.state ~= "attack" and obj.name == self.name then
  3739. -- But owned mobs will not attack their owners.
  3740. if not (obj.owner == name) then
  3741. do_attack(obj, hitter)
  3742. end
  3743. end
  3744. -- have owned mobs attack player threat
  3745. if name ~= "" and obj.owner == name and obj.owner_loyal then
  3746. do_attack(obj, self.object)
  3747. end
  3748. end
  3749. end
  3750. end
  3751. -- export!
  3752. function mobs.mob_punch(self, hitter, tflp, tool_capabilities, dir)
  3753. return mob_punch(self, hitter, tflp, tool_capabilities, dir)
  3754. end
  3755. -- get entity staticdata
  3756. local function mob_staticdata(self)
  3757. -- remove mob when out of range unless tamed
  3758. if remove_far
  3759. and self.remove_ok
  3760. and self.type ~= "npc"
  3761. and self.state ~= "attack"
  3762. and not self.tamed
  3763. and self.lifetimer < 20000 then
  3764. --print ("REMOVED " .. self.name)
  3765. -- Mark for removal as last action on mob_step().
  3766. self.mkrm = true
  3767. return ""-- nil
  3768. end
  3769. self.remove_ok = true
  3770. self.attack = nil
  3771. self.following = nil
  3772. self.state = "stand"
  3773. self.substate = ""
  3774. -- used to rotate older mobs
  3775. if self.drawtype and self.drawtype == "side" then
  3776. self.rotate = rad(90)
  3777. end
  3778. local tmp = {}
  3779. for _,stat in pairs(self) do
  3780. local t = type(stat)
  3781. if t ~= "function" and t ~= "nil" and t ~= "userdata" and _ ~= "_cmi_components" then
  3782. tmp[_] = self[_]
  3783. end
  3784. end
  3785. --print('===== '..self.name..'\n'.. dump(tmp)..'\n=====\n')
  3786. return minetest.serialize(tmp)
  3787. end
  3788. -- export!
  3789. function mobs.mob_staticdata(self)
  3790. return mob_staticdata(self)
  3791. end
  3792. -- Activate mob and reload settings.
  3793. local function mob_activate(self, staticdata, def, dtime)
  3794. -- Remove mob if activated during daytime and has 'daytime_despawn'.
  3795. if def.daytime_despawn then
  3796. local tod = (minetest.get_timeofday() or 0) * 24000
  3797. if tod > 4500 and tod < 19500 then
  3798. -- Daylight, but mob despawns at daytime.
  3799. -- Mark for removal as last action on mob_step().
  3800. self.mkrm = true
  3801. return
  3802. end
  3803. end
  3804. -- Remove mob if outside realm dimensions.
  3805. if not rc.is_valid_realm_pos(self.object:get_pos()) then
  3806. -- Mark for removal as last action on mob_step().
  3807. self.mkrm = true
  3808. return
  3809. end
  3810. -- load entity variables
  3811. local tmp = minetest.deserialize(staticdata)
  3812. if tmp then
  3813. for _, stat in pairs(tmp) do
  3814. self[_] = stat
  3815. end
  3816. end
  3817. -- Do select random texture, set model and size.
  3818. if not self.base_texture then
  3819. -- Do compatiblity with old simple mobs textures.
  3820. if def.textures and type(def.textures[1]) == "string" then
  3821. def.textures = {def.textures}
  3822. end
  3823. self.base_texture = def.textures and def.textures[random(1, #def.textures)]
  3824. self.base_mesh = def.mesh
  3825. self.base_size = self.visual_size
  3826. self.base_colbox = self.collisionbox
  3827. self.base_selbox = self.selectionbox
  3828. end
  3829. -- for current mobs that dont have this set
  3830. if not self.base_selbox then
  3831. self.base_selbox = self.selectionbox or self.base_colbox
  3832. end
  3833. -- set texture, model and size
  3834. local textures = self.base_texture
  3835. local mesh = self.base_mesh
  3836. local vis_size = self.base_size
  3837. local colbox = self.base_colbox
  3838. local selbox = self.base_selbox
  3839. -- specific texture if gotten
  3840. if self.gotten == true and def.gotten_texture then
  3841. textures = def.gotten_texture
  3842. end
  3843. -- specific mesh if gotten
  3844. if self.gotten == true and def.gotten_mesh then
  3845. mesh = def.gotten_mesh
  3846. end
  3847. -- set child objects to half size
  3848. if self.child == true then
  3849. vis_size = {
  3850. x = self.base_size.x * .5,
  3851. y = self.base_size.y * .5,
  3852. }
  3853. if def.child_texture then
  3854. textures = def.child_texture[1]
  3855. end
  3856. colbox = {
  3857. self.base_colbox[1] * .5,
  3858. self.base_colbox[2] * .5,
  3859. self.base_colbox[3] * .5,
  3860. self.base_colbox[4] * .5,
  3861. self.base_colbox[5] * .5,
  3862. self.base_colbox[6] * .5
  3863. }
  3864. selbox = {
  3865. self.base_selbox[1] * .5,
  3866. self.base_selbox[2] * .5,
  3867. self.base_selbox[3] * .5,
  3868. self.base_selbox[4] * .5,
  3869. self.base_selbox[5] * .5,
  3870. self.base_selbox[6] * .5
  3871. }
  3872. end
  3873. if self.health == 0 then
  3874. self.health = random (self.hp_min, self.hp_max)
  3875. end
  3876. -- Pathfinding init.
  3877. self.path = {}
  3878. self.path.way = {} -- path to follow, table of positions
  3879. self.path.lastpos = {x = 0, y = 0, z = 0}
  3880. self.path.following = false -- currently following path?
  3881. self.path.pos_rec_timer = 0
  3882. self.path.find_path_timer = 0
  3883. self.path.putnode_timer = 0
  3884. self.path.los_counter = 0
  3885. self.path.los_check = 0
  3886. self.path.target = nil
  3887. -- Avoidance "avoid" state init.
  3888. self.avoid = {}
  3889. self.avoid.target = nil
  3890. self.avoid.timer = 0
  3891. -- Dig/build state init.
  3892. self.digbuild = {}
  3893. self.digbuild.target = nil
  3894. self.digbuild.node_timer = 0
  3895. -- Adjust the chance to use pathfinding on a per-entity basis.
  3896. if self.pathfinding and self.pathfinding ~= 0 then
  3897. -- If pathfinding is enabled, by default chance is 100%.
  3898. local chance = self.pathfinding_chance or 100
  3899. local res = random(1, 100)
  3900. if res > chance then
  3901. self.pathfinding = 0
  3902. end
  3903. end
  3904. -- mob defaults
  3905. self.object:set_armor_groups({immortal = 1, fleshy = self.armor})
  3906. self.old_y = self.object:get_pos().y
  3907. self.old_health = self.health
  3908. self.sounds.distance = self.sounds.distance or 10
  3909. self.textures = textures
  3910. self.mesh = mesh
  3911. self.collisionbox = colbox
  3912. self.selectionbox = selbox
  3913. self.visual_size = vis_size
  3914. self.standing_in = "air"
  3915. self.standing_on = "air"
  3916. -- check existing nametag
  3917. if not self.nametag then
  3918. self.nametag = def.nametag
  3919. end
  3920. -- set anything changed above
  3921. self.object:set_properties(self)
  3922. set_yaw(self, (random(0, 360) - 180) / 180 * pi, 6)
  3923. update_tag(self)
  3924. set_animation(self, "stand")
  3925. -- run on_spawn function if found
  3926. if self.on_spawn and not self.on_spawn_run then
  3927. if self.on_spawn(self) then
  3928. self.on_spawn_run = true -- if true, set flag to run once only
  3929. end
  3930. end
  3931. -- run after_activate
  3932. if def.after_activate then
  3933. def.after_activate(self, staticdata, def, dtime)
  3934. end
  3935. end
  3936. -- export!
  3937. function mobs.mob_activate(self, staticdata, def, dtime)
  3938. return mob_activate(self, staticdata, def, dtime)
  3939. end
  3940. local function smooth_rotate(self)
  3941. -- smooth rotation by ThomasMonroe314
  3942. if self.delay and self.delay > 0 then
  3943. local yaw = self.object:get_yaw()
  3944. if self.delay == 1 then
  3945. yaw = self.target_yaw
  3946. else
  3947. local dif = abs(yaw - self.target_yaw)
  3948. if yaw > self.target_yaw then
  3949. if dif > pi then
  3950. dif = 2 * pi - dif -- need to add
  3951. yaw = yaw + dif / self.delay
  3952. else
  3953. yaw = yaw - dif / self.delay -- need to subtract
  3954. end
  3955. elseif yaw < self.target_yaw then
  3956. if dif > pi then
  3957. dif = 2 * pi - dif
  3958. yaw = yaw - dif / self.delay -- need to subtract
  3959. else
  3960. yaw = yaw + dif / self.delay -- need to add
  3961. end
  3962. end
  3963. if yaw > (pi * 2) then yaw = yaw - (pi * 2) end
  3964. if yaw < 0 then yaw = yaw + (pi * 2) end
  3965. end
  3966. self.delay = self.delay - 1
  3967. self.object:set_yaw(yaw)
  3968. end
  3969. -- end rotation
  3970. end
  3971. local function stuck_timer(self, dtime, pos)
  3972. -- Set up 'is_stuck' state flag/timer. This is a timer which clocks how long
  3973. -- the mob has not moved for. It is clamped whenever it exceeds 100 seconds,
  3974. -- and reset when the mob's position changes.
  3975. if (self.wanted_velocity or 0) > 0 then
  3976. self.stuck_timer = (self.stuck_timer or 0) + dtime
  3977. if self.stuck_timer > 100 then self.stuck_timer = 100 end
  3978. if v_distance(self.last_pos or pos, pos) > 0.001 then
  3979. self.stuck_timer = 0
  3980. end
  3981. self.last_pos = pos
  3982. self.stand_timer = 0
  3983. else
  3984. -- If the wanted velocity is zero, the stuck-timer does not run.
  3985. -- We are obviously not stuck in such a case!
  3986. self.last_pos = pos
  3987. self.stuck_timer = 0
  3988. self.stand_timer = (self.stand_timer or 0) + dtime
  3989. if self.stand_timer > 100 then self.stand_timer = 100 end
  3990. end
  3991. end
  3992. local function do_punch_timer(self, dtime)
  3993. self.punch_timer = (self.punch_timer or 0) - dtime
  3994. if self.punch_timer < 0 then
  3995. self.punch_timer = 0
  3996. end
  3997. end
  3998. -- Here is the main mob function.
  3999. local function mob_step(self, dtime)
  4000. -- The final (actually first) action of mob_step().
  4001. -- If the mob was marked for removal, we call self.object:remove() here.
  4002. -- This: self.object:remove(), should not be called anywhere else!
  4003. if self.mkrm then self.object:remove(); return end
  4004. -- Stupid spurious errors [MustTest]. Implies our object does not exist.
  4005. local pos = self.object:get_pos()
  4006. if not pos then return end
  4007. -- Manage stuck-timer.
  4008. stuck_timer(self, dtime, pos)
  4009. -- When lifetimer expires, remove mob.
  4010. do_lifetimer(self, pos)
  4011. -- Get what nodes the mob is standing in/on.
  4012. update_foot_nodes(self, pos, dtime)
  4013. -- Check if falling, flying, floating.
  4014. falling(self, pos)
  4015. -- Do smooth rotation.
  4016. smooth_rotate(self)
  4017. -- Manage punch timer.
  4018. do_punch_timer(self, dtime)
  4019. -- Knockback timer. If set, the mob will do nothing until it expires!
  4020. -- Typically this would be set for something like a knockback effect.
  4021. if self.pause_timer > 0 then
  4022. self.pause_timer = self.pause_timer - dtime
  4023. return
  4024. end
  4025. -- Run custom function (defined in mob's script file).
  4026. if self.do_custom then
  4027. -- when false skip going any further
  4028. if self.do_custom(self, dtime) == false then
  4029. return
  4030. end
  4031. end
  4032. -- Environmental damage timer (every 1 second).
  4033. self.env_damage_timer = self.env_damage_timer + dtime
  4034. if self.env_damage_timer >= 1 then
  4035. self.env_damage_timer = 0
  4036. -- Check for environmental damage (water, fire, lava, etc.).
  4037. do_env_damage(self)
  4038. -- Node replace check (cow eats grass, etc.).
  4039. replace(self, pos)
  4040. -- Debug path display.
  4041. highlight_path(self)
  4042. end
  4043. -- Mob plays random sound at times.
  4044. self.sound_timer = (self.sound_timer or 0) + dtime
  4045. if self.sound_timer >= 1 then
  4046. if random(1, 100) == 1 then
  4047. mob_sound(self, self.sounds.random)
  4048. end
  4049. self.sound_timer = 0
  4050. end
  4051. -- This code forces state logic to only run once per second, unless the
  4052. -- current state is flagged to execute continuously. This reduces load on the
  4053. -- server.
  4054. local sm = state_machine
  4055. if not sm[self.state].continuous then
  4056. self.logic_timer = (self.logic_timer or 0) + dtime
  4057. if self.logic_timer < 1 then return end
  4058. self.logic_timer = 0
  4059. -- Since we return early if time is less than 1 second, once timer fires,
  4060. -- we need to pass a 'dtime' of 1 to the logic that follows.
  4061. dtime = 1
  4062. end
  4063. -- Limit the general scanning functions to once per second.
  4064. self.scan_timer = (self.scan_timer or 0) + dtime
  4065. if self.scan_timer >= 1 then
  4066. self.scan_timer = 0
  4067. -- For belligerent mobs, scan for victims to attack.
  4068. general_attack(self)
  4069. -- For skittish mobs, scan for things to run away from.
  4070. runaway_from(self)
  4071. -- Mob reproduction.
  4072. attempt_breed(self)
  4073. -- Periodically refocus attacking mobs.
  4074. refocus_attack(self)
  4075. -- Scan for things to follow around.
  4076. follow_something(self)
  4077. end
  4078. do_states(self, dtime)
  4079. end
  4080. -- export!
  4081. function mobs.mob_step(self, dtime)
  4082. return mob_step(self, dtime)
  4083. end
  4084. -- Default function when mobs are blown up with TNT.
  4085. local function do_tnt(obj, damage)
  4086. obj.object:punch(obj.object, 1.0, {
  4087. full_punch_interval = 1.0,
  4088. damage_groups = {fleshy = damage},
  4089. }, nil)
  4090. return false, true, {}
  4091. end
  4092. -- export!
  4093. function mobs.do_tnt(obj, damage)
  4094. return do_tnt(obj, damage)
  4095. end
  4096. local function first_or_second(arg1, arg2)
  4097. if type(arg1) ~= "nil" then
  4098. return arg1
  4099. else
  4100. return arg2
  4101. end
  4102. end
  4103. -- register mob entity function
  4104. if not mobs.registered then
  4105. mobs.spawning_mobs = {}
  4106. -- Register mob function.
  4107. mobs.register_mob = function(name, def)
  4108. mobs.spawning_mobs[name] = true
  4109. minetest.register_entity(name, {
  4110. -- Warning: this parameter is set by the engine anway!
  4111. name = name,
  4112. _name = name,
  4113. mob = true,
  4114. type = def.type,
  4115. armor_level = def.armor_level or 0,
  4116. description = def.description,
  4117. stepheight = def.stepheight or 1.1,
  4118. attack_type = def.attack_type,
  4119. fly = def.fly,
  4120. fly_in = def.fly_in or "air",
  4121. owner = def.owner or "",
  4122. order = def.order or "",
  4123. on_die = def.on_die,
  4124. do_custom = def.do_custom,
  4125. -- The number of nodes a mob can jump over. Actual jump velocity is
  4126. -- calculated from this. Supported values are 1, 2, 3.
  4127. jump_height = def.jump_height or 1,
  4128. drawtype = def.drawtype, -- DEPRECATED, use rotate instead
  4129. rotate = rad(def.rotate or 0), -- 0=front, 90=side, 180=back, 270=side2
  4130. lifetimer = def.lifetimer or 180, -- 3 minutes
  4131. hp_min = (def.hp_min or 5) * difficulty,
  4132. hp_max = (def.hp_max or 10) * difficulty,
  4133. physical = true,
  4134. collisionbox = def.collisionbox or {-0.25, -0.25, -0.25, 0.25, 0.25, 0.25},
  4135. selectionbox = def.selectionbox or def.collisionbox,
  4136. visual = def.visual,
  4137. visual_size = def.visual_size or {x = 1, y = 1},
  4138. mesh = def.mesh,
  4139. makes_footstep_sound = def.makes_footstep_sound or false,
  4140. view_range = def.view_range or 5,
  4141. walk_velocity = def.walk_velocity or 1,
  4142. run_velocity = def.run_velocity or 2,
  4143. sprint_velocity = def.sprint_velocity or def.run_velocity or 2,
  4144. -- Mob may do an exact amount of damage.
  4145. -- But if min/max damage values are set (non-nil, non-0), those are used
  4146. -- instead.
  4147. damage = (def.damage or 0) * difficulty,
  4148. damage_min = (def.damage_min or 0) * difficulty,
  4149. damage_max = (def.damage_max or 0) * difficulty,
  4150. damage_group = def.damage_group,
  4151. daytime_despawn = def.daytime_despawn,
  4152. on_despawn = def.on_despawn,
  4153. light_damage = def.light_damage or 0,
  4154. water_damage = def.water_damage or 0,
  4155. lava_damage = def.lava_damage or 0,
  4156. fire_damage = def.fire_damage or 0,
  4157. suffocation = def.suffocation or 2,
  4158. lava_annihilates = first_or_second(def.lava_annihilates, true),
  4159. makes_bones_in_lava = first_or_second(def.makes_bones_in_lava, true),
  4160. fall_damage = def.fall_damage or 1,
  4161. fall_speed = def.fall_speed or -10, -- must be lower than -2 (default: -10)
  4162. drops = def.drops or {},
  4163. armor = def.armor or 100,
  4164. on_rightclick = def.on_rightclick,
  4165. arrow = def.arrow,
  4166. shoot_interval = def.shoot_interval,
  4167. sounds = def.sounds or {},
  4168. animation = def.animation,
  4169. follow = def.follow,
  4170. jump = def.jump ~= false,
  4171. walk_chance = def.walk_chance or 50,
  4172. --fov = def.fov or 120,
  4173. passive = def.passive or false,
  4174. knock_back = def.knock_back ~= false,
  4175. blood_amount = def.blood_amount or 5,
  4176. blood_texture = def.blood_texture or "mobs_blood.png",
  4177. shoot_offset = def.shoot_offset or 0,
  4178. floats = def.floats or 1, -- floats in water by default
  4179. replace_rate = def.replace_rate,
  4180. replace_what = def.replace_what,
  4181. replace_with = def.replace_with,
  4182. replace_offset = def.replace_offset or 0,
  4183. on_replace = def.on_replace,
  4184. -- Feature added by MustTest.
  4185. replace_range = def.replace_range or 1,
  4186. despawns_in_dark_caves = def.despawns_in_dark_caves or false,
  4187. timer = 0,
  4188. env_damage_timer = 0, -- only used when state = "attack"
  4189. tamed = false,
  4190. pause_timer = 0,
  4191. horny = false,
  4192. hornytimer = 0,
  4193. child = false,
  4194. gotten = false,
  4195. health = 0,
  4196. reach = def.reach or 3,
  4197. punch_reach = def.punch_reach or def.reach or 3,
  4198. htimer = 0,
  4199. texture_list = def.textures,
  4200. child_texture = def.child_texture,
  4201. docile_by_day = def.docile_by_day or false,
  4202. time_of_day = 0.5,
  4203. fear_height = def.fear_height or 0,
  4204. runaway = def.runaway,
  4205. runaway_timer = 0,
  4206. pathfinding = def.pathfinding or 0,
  4207. pathfinding_chance = def.pathfinding_chance,
  4208. place_node = def.place_node,
  4209. immune_to = def.immune_to or {},
  4210. explosion_radius = def.explosion_radius,
  4211. explosion_damage_radius = def.explosion_damage_radius,
  4212. explosion_timer = def.explosion_timer or 3,
  4213. allow_fuse_reset = def.allow_fuse_reset ~= false,
  4214. stop_to_explode = def.stop_to_explode ~= false,
  4215. custom_attack = def.custom_attack,
  4216. double_melee_attack = def.double_melee_attack,
  4217. dogshoot_switch = def.dogshoot_switch,
  4218. dogshoot_count = 0,
  4219. dogshoot_count_max = def.dogshoot_count_max or 5,
  4220. dogshoot_count2_max = def.dogshoot_count2_max or (def.dogshoot_count_max or 5),
  4221. group_attack = def.group_attack or false,
  4222. attack_monsters = def.attack_monsters or false,
  4223. attack_animals = def.attack_animals or false,
  4224. attack_players = def.attack_players ~= false,
  4225. attack_npcs = def.attack_npcs ~= false,
  4226. specific_attack = def.specific_attack,
  4227. runaway_from = def.runaway_from,
  4228. owner_loyal = def.owner_loyal,
  4229. facing_fence = false,
  4230. ignore_invisibility = def.ignore_invisibility,
  4231. pathing_radius = def.pathing_radius,
  4232. max_node_dig_level = def.max_node_dig_level,
  4233. --hunt_players = def.hunt_players,
  4234. hunt_chance = def.hunt_chance or 0,
  4235. -- The meaning of 'attack_chance' is inverted in order to make more sense [MustTest].
  4236. attack_chance = def.attack_chance or 95,
  4237. show_health = def.show_health,
  4238. _cmi_is_mob = true,
  4239. punch_target = def.punch_target,
  4240. on_spawn = def.on_spawn,
  4241. on_blast = def.on_blast or function(...) return mobs.do_tnt(...) end,
  4242. on_step = function(...) return mobs.mob_step(...) end,
  4243. do_punch = def.do_punch,
  4244. on_punch = function(...) return mobs.mob_punch(...) end,
  4245. on_breed = def.on_breed,
  4246. on_grown = def.on_grown,
  4247. on_activate = function(self, staticdata, dtime)
  4248. return mobs.mob_activate(self, staticdata, def, dtime)
  4249. end,
  4250. get_staticdata = function(self)
  4251. return mobs.mob_staticdata(self)
  4252. end,
  4253. })
  4254. end -- END mobs:register_mob function
  4255. end
  4256. local function arrow_step(self, dtime, def)
  4257. self.timer = self.timer + 1
  4258. local pos = self.object:get_pos()
  4259. if not pos then
  4260. return
  4261. end
  4262. -- Remove expired arrows.
  4263. if self.switch == 0
  4264. or self.timer > 150
  4265. or not within_limits(pos, 0) then
  4266. self.object:remove()
  4267. return
  4268. end
  4269. -- does arrow have a tail (fireball)
  4270. if def.tail
  4271. and def.tail == 1
  4272. and def.tail_texture then
  4273. minetest.add_particle({
  4274. pos = pos,
  4275. velocity = {x = 0, y = 0, z = 0},
  4276. acceleration = {x = 0, y = 0, z = 0},
  4277. expirationtime = def.expire or 0.25,
  4278. collisiondetection = false,
  4279. texture = def.tail_texture,
  4280. size = def.tail_size or 5,
  4281. glow = def.glow or 0,
  4282. })
  4283. end
  4284. if self.hit_node then
  4285. -- Always round node position before passing it to code that probably
  4286. -- assumes that position is an integer (failure to do this can result in
  4287. -- coordinate problems in the engine)!
  4288. local rpos = v_round(pos)
  4289. local node = node_ok(rpos).name
  4290. local ndef = minetest.reg_ns_nodes[node]
  4291. if not ndef or ndef.walkable then
  4292. self.hit_node(self, rpos, node)
  4293. if self.drop == true then
  4294. pos.y = pos.y + 1
  4295. self.lastpos = (self.lastpos or pos)
  4296. minetest.add_item(self.lastpos, self.object:get_luaentity().name)
  4297. end
  4298. self.object:remove() ; -- print ("hit node")
  4299. return
  4300. end
  4301. end
  4302. if self.hit_player or self.hit_mob then
  4303. -- Find target that we hit.
  4304. for _, target in pairs(minetest.get_objects_inside_radius(pos, 1.5)) do
  4305. if self.hit_player and target:is_player() then
  4306. self.hit_player(self, target)
  4307. self.object:remove()
  4308. return
  4309. end
  4310. local entity = target:get_luaentity()
  4311. if entity and self.hit_mob and entity._cmi_is_mob == true
  4312. and target ~= self.owner_obj
  4313. and entity.name ~= self.name then
  4314. -- Check that target actually exists.
  4315. if target:get_pos() then
  4316. self.hit_mob(self, target)
  4317. self.object:remove()
  4318. return
  4319. end
  4320. end
  4321. end
  4322. end
  4323. self.lastpos = pos
  4324. end
  4325. -- export!
  4326. function mobs.arrow_step(self, dtime, def)
  4327. return arrow_step(self, dtime, def)
  4328. end
  4329. -- register mob arrow entity function
  4330. if not mobs.registered then
  4331. -- register arrow for shoot attack
  4332. function mobs.register_arrow(name, def)
  4333. if not name or not def then return end -- errorcheck
  4334. minetest.register_entity(name, {
  4335. physical = false,
  4336. visual = def.visual,
  4337. visual_size = def.visual_size,
  4338. textures = def.textures,
  4339. velocity = def.velocity,
  4340. hit_player = def.hit_player,
  4341. hit_node = def.hit_node,
  4342. hit_mob = def.hit_mob,
  4343. drop = def.drop or false, -- drops arrow as registered item when true
  4344. collisionbox = {0, 0, 0, 0, 0, 0}, -- remove box around arrows
  4345. timer = 0,
  4346. switch = 0,
  4347. rotate = def.rotate,
  4348. automatic_face_movement_dir = def.rotate
  4349. and (def.rotate - (pi / 180)) or false,
  4350. on_activate = def.on_activate,
  4351. on_step = def.on_step or function(self, dtime)
  4352. return mobs.arrow_step(self, dtime, def)
  4353. end,
  4354. })
  4355. end
  4356. end
  4357. -- Spawner item.
  4358. -- Note: This also introduces the “spawn_egg” group:
  4359. -- * spawn_egg=1: Spawn egg (generic mob, no metadata)
  4360. -- * spawn_egg=2: Spawn egg (captured/tamed mob, metadata)
  4361. if not mobs.registered then
  4362. mobs.register_egg = function(mob, desc, background, addegg, no_creative)
  4363. local invimg = background
  4364. if addegg == 1 then
  4365. invimg = "mobs_egg.png^(" .. background .. "^[mask:mobs_egg_overlay.png)"
  4366. elseif addegg == 0 then
  4367. invimg = background
  4368. end
  4369. -- Register new spawn egg containing mob information
  4370. minetest.register_craftitem(mob .. "_set", {
  4371. description = desc .. " Spawn Egg (Tamed)",
  4372. inventory_image = invimg,
  4373. groups = {
  4374. not_in_creative_inventory = 1,
  4375. not_in_craft_guide = 1,
  4376. spawn_egg = 2,
  4377. },
  4378. stack_max = 1,
  4379. on_place = function(itemstack, placer, pointed_thing)
  4380. local pos = pointed_thing.above
  4381. -- Am I clicking on something with existing on_rightclick function?
  4382. local under = minetest.get_node(pointed_thing.under)
  4383. local def = minetest.registered_nodes[under.name]
  4384. if def and def.on_rightclick then
  4385. return def.on_rightclick(pointed_thing.under, under, placer, itemstack)
  4386. end
  4387. if pos and within_limits(pos, 0) then
  4388. if not minetest.registered_entities[mob] then
  4389. minetest.chat_send_player(name, "# Server: Creature type not defined!")
  4390. return
  4391. end
  4392. pos.y = pos.y + 1
  4393. local data = itemstack:get_metadata()
  4394. local mob = minetest.add_entity(pos, mob, data)
  4395. local ent = mob:get_luaentity()
  4396. if not ent then mob:remove()
  4397. minetest.chat_send_player(name, "# Server: Failed to revive creature!")
  4398. return
  4399. end
  4400. -- Set owner if not a monster or NPC.
  4401. if ent.type ~= "monster" and ent.type ~= "npc" then
  4402. ent.owner = placer:get_player_name()
  4403. ent.tamed = true
  4404. end
  4405. -- Since mob is unique we remove egg once spawned.
  4406. itemstack:take_item()
  4407. end
  4408. return itemstack
  4409. end,
  4410. })
  4411. -- Register old stackable mob egg.
  4412. minetest.register_craftitem(mob, {
  4413. description = desc .. " Spawn Egg",
  4414. inventory_image = invimg,
  4415. groups = {
  4416. not_in_creative_inventory = 1,
  4417. not_in_craft_guide = 1,
  4418. spawn_egg = 1,
  4419. },
  4420. on_place = function(itemstack, placer, pointed_thing)
  4421. local pos = pointed_thing.above
  4422. local name = placer:get_player_name()
  4423. if pos and within_limits(pos, 0) then
  4424. if not minetest.registered_entities[mob] then
  4425. minetest.chat_send_player(name, "# Server: Creature type not defined!")
  4426. return
  4427. end
  4428. pos.y = pos.y + 1
  4429. local mob = minetest.add_entity(pos, mob)
  4430. local ent = mob:get_luaentity()
  4431. if not ent then mob:remove()
  4432. minetest.chat_send_player(name, "# Server: Failed to summon creature!")
  4433. return
  4434. end
  4435. -- Don't set owner if monster or NPC or sneak pressed.
  4436. if ent.type ~= "monster" and ent.type ~= "npc" then
  4437. if not placer:get_player_control().sneak then
  4438. ent.owner = placer:get_player_name()
  4439. ent.tamed = true
  4440. end
  4441. end
  4442. end
  4443. itemstack:take_item()
  4444. return itemstack
  4445. end,
  4446. })
  4447. end
  4448. end
  4449. -- Capture critter (thanks to blert2112 for idea).
  4450. function mobs.capture_mob(self, clicker, chance_hand, chance_net, chance_lasso, force_take, replacewith)
  4451. if self.child
  4452. or not clicker:is_player()
  4453. or not clicker:get_inventory() then
  4454. return false
  4455. end
  4456. -- get name of clicked mob
  4457. local mobname = self.name
  4458. -- if not nil change what will be added to inventory
  4459. if replacewith then
  4460. mobname = replacewith
  4461. end
  4462. local name = clicker:get_player_name()
  4463. local tool = clicker:get_wielded_item()
  4464. -- are we using hand, net or lasso to pick up mob?
  4465. if tool:get_name() ~= ""
  4466. and tool:get_name() ~= "mobs:net"
  4467. and tool:get_name() ~= "mobs:lasso" then
  4468. return false
  4469. end
  4470. -- Is mob tamed?
  4471. if self.tamed == false and force_take == false then
  4472. minetest.chat_send_player(name, "# Server: Animal not tamed!")
  4473. return true -- false
  4474. end
  4475. -- Cannot pick up if not owner.
  4476. if self.owner ~= name and force_take == false then
  4477. minetest.chat_send_player(name, "# Server: Player <" .. rename.gpn(self.owner) .. "> is owner!")
  4478. return true -- false
  4479. end
  4480. if clicker:get_inventory():room_for_item("main", mobname) then
  4481. -- Was mob clicked with hand, net, or lasso?
  4482. local chance = 0
  4483. local tool = clicker:get_wielded_item()
  4484. if tool:get_name() == "" then
  4485. chance = chance_hand
  4486. elseif tool:get_name() == "mobs:net" then
  4487. chance = chance_net
  4488. tool:add_wear(4000) -- 17 uses
  4489. clicker:set_wielded_item(tool)
  4490. elseif tool:get_name() == "mobs:lasso" then
  4491. chance = chance_lasso
  4492. tool:add_wear(650) -- 100 uses
  4493. clicker:set_wielded_item(tool)
  4494. end
  4495. -- calculate chance.. add to inventory if successful?
  4496. if chance > 0 and random(1, 100) <= chance then
  4497. -- default mob egg
  4498. local new_stack = ItemStack(mobname)
  4499. -- add special mob egg with all mob information
  4500. -- unless 'replacewith' contains new item to use
  4501. if not replacewith then
  4502. new_stack = ItemStack(mobname .. "_set")
  4503. local tmp = {}
  4504. for _,stat in pairs(self) do
  4505. local t = type(stat)
  4506. if t ~= "function"
  4507. and t ~= "nil"
  4508. and t ~= "userdata" then
  4509. tmp[_] = self[_]
  4510. end
  4511. end
  4512. local data_str = minetest.serialize(tmp)
  4513. new_stack:set_metadata(data_str)
  4514. end
  4515. local inv = clicker:get_inventory()
  4516. if inv:room_for_item("main", new_stack) then
  4517. inv:add_item("main", new_stack)
  4518. else
  4519. minetest.add_item(clicker:get_pos(), new_stack)
  4520. end
  4521. -- Mark for removal as last action on mob_step().
  4522. self.mkrm = true
  4523. mob_sound(self, "default_place_node_hard")
  4524. elseif chance ~= 0 then
  4525. minetest.chat_send_player(name, "# Server: Missed!")
  4526. mob_sound(self, "mobs_swing")
  4527. end
  4528. end
  4529. end
  4530. -- Make tables persistent even when file reloaded.
  4531. if not mobs.registered then
  4532. mobs.nametagdata = {}
  4533. mobs.nametagdata.mob_obj = {}
  4534. mobs.nametagdata.mob_sta = {}
  4535. end
  4536. local mob_obj = mobs.nametagdata.mob_obj
  4537. local mob_sta = mobs.nametagdata.mob_sta
  4538. -- Feeding, taming and breeding (thanks blert2112).
  4539. function mobs.feed_tame(self, clicker, feed_count, breed, tame)
  4540. if not self.follow then
  4541. return false
  4542. end
  4543. -- can eat/tame with item in hand
  4544. if follow_holding(self, clicker) then
  4545. -- if not in creative then take item
  4546. if not creative then
  4547. local item = clicker:get_wielded_item()
  4548. item:take_item()
  4549. clicker:set_wielded_item(item)
  4550. end
  4551. -- increase health
  4552. self.health = self.health + 4
  4553. if self.health >= self.hp_max then
  4554. self.health = self.hp_max
  4555. if self.htimer < 1 then
  4556. minetest.chat_send_player(clicker:get_player_name(), "# Server: Mob has full health!")
  4557. self.htimer = 5
  4558. end
  4559. end
  4560. self.object:set_hp(self.health)
  4561. update_tag(self)
  4562. -- make children grow quicker
  4563. if self.child == true then
  4564. self.hornytimer = self.hornytimer + 20
  4565. return true
  4566. end
  4567. -- feed and tame
  4568. self.food = (self.food or 0) + 1
  4569. if self.food >= feed_count then
  4570. self.food = 0
  4571. if breed and self.hornytimer == 0 then
  4572. self.horny = true
  4573. end
  4574. self.gotten = false
  4575. if tame then
  4576. if self.tamed == false then
  4577. minetest.chat_send_player(clicker:get_player_name(), "# Server: Mob has been tamed!")
  4578. end
  4579. self.tamed = true
  4580. if not self.owner or self.owner == "" then
  4581. self.owner = clicker:get_player_name()
  4582. end
  4583. end
  4584. -- make sound when fed so many times
  4585. mob_sound(self, self.sounds.random)
  4586. end
  4587. return true
  4588. end
  4589. local item = clicker:get_wielded_item()
  4590. -- if mob has been tamed you can name it with a nametag
  4591. if item:get_name() == "mobs:nametag"
  4592. and clicker:get_player_name() == self.owner then
  4593. local name = clicker:get_player_name()
  4594. -- store mob and nametag stack in external variables
  4595. mob_obj[name] = self
  4596. mob_sta[name] = item
  4597. local tag = self.nametag or ""
  4598. minetest.show_formspec(name, "mobs_nametag", "size[8,4]"
  4599. .. default.gui_bg
  4600. .. default.gui_bg_img
  4601. .. "field[0.5,1;7.5,0;name;" .. minetest.formspec_escape("Enter name:") .. ";" .. tag .. "]"
  4602. .. "button_exit[2.5,3.5;3,1;mob_rename;" .. minetest.formspec_escape("Rename") .. "]")
  4603. end
  4604. return false
  4605. end
  4606. function mobs.nametag_receive_fields(player, formname, fields)
  4607. -- right-clicked with nametag and name entered?
  4608. if formname == "mobs_nametag"
  4609. and fields.name
  4610. and fields.name ~= "" then
  4611. local name = player:get_player_name()
  4612. if not mob_obj[name]
  4613. or not mob_obj[name].object then
  4614. return
  4615. end
  4616. -- make sure nametag is being used to name mob
  4617. local item = player:get_wielded_item()
  4618. if item:get_name() ~= "mobs:nametag" then
  4619. return
  4620. end
  4621. -- limit name entered to 64 characters long
  4622. if string.len(fields.name) > 64 then
  4623. fields.name = string.sub(fields.name, 1, 64)
  4624. end
  4625. -- update nametag
  4626. mob_obj[name].nametag = fields.name
  4627. update_tag(mob_obj[name])
  4628. -- if not in creative then take item
  4629. if not mobs.is_creative(name) then
  4630. mob_sta[name]:take_item()
  4631. player:set_wielded_item(mob_sta[name])
  4632. end
  4633. -- reset external variables
  4634. mob_obj[name] = nil
  4635. mob_sta[name] = nil
  4636. end
  4637. end
  4638. -- inspired by blockmen's nametag mod
  4639. if not mobs.registered then
  4640. minetest.register_on_player_receive_fields(function(...)
  4641. return mobs.nametag_receive_fields(...)
  4642. end)
  4643. end
  4644. -- compatibility function for old entities to new modpack entities
  4645. if not mobs.registered then
  4646. function mobs.alias_mob(old_name, new_name)
  4647. -- spawn egg
  4648. minetest.register_alias(old_name, new_name)
  4649. -- entity
  4650. minetest.register_entity(":" .. old_name, {
  4651. physical = false,
  4652. on_activate = function(self)
  4653. if minetest.registered_entities[new_name] then
  4654. minetest.add_entity(self.object:get_pos(), new_name)
  4655. end
  4656. -- Remove mob immediately, as last step of this function.
  4657. -- Controls returns to engine.
  4658. self.object:remove()
  4659. self.mkrm = true
  4660. end
  4661. })
  4662. end
  4663. end
  4664. -- Register as a reloadable file.
  4665. if not mobs.registered then
  4666. local c = "mobs:api"
  4667. local f = mobs.modpath .. "/api.lua"
  4668. reload.register_file(c, f, false)
  4669. mobs.registered = true
  4670. end