api.lua 145 KB

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